diff --git a/readme.md b/readme.md index 41ffc162..58039726 100644 --- a/readme.md +++ b/readme.md @@ -158,7 +158,9 @@ Each of the generator properties (like `name`, `address`, and `lorem`) are calle ### `Faker\Provider\Base` randomDigit // 7 + randomDigitNotNull // 5 randomNumber($nbDigits = NULL) // 79907610 + randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932 randomLetter // 'b' randomElement($array = array ('a','b','c')) // 'b' numerify($string = '###') // '609' diff --git a/src/Faker/Provider/Base.php b/src/Faker/Provider/Base.php index 7f64bfe9..16b74993 100644 --- a/src/Faker/Provider/Base.php +++ b/src/Faker/Provider/Base.php @@ -63,6 +63,35 @@ class Base return mt_rand(0, pow(10, $nbDigits) - 1); } + /** + * Return a random float number + * + * @param int $nbMaxDecimals + * @param int|float $min + * @param int|float $max + * @example 48.8932 + * + * @return float + */ + public static function randomFloat($nbMaxDecimals = null, $min = 0, $max = null) + { + if (null === $nbMaxDecimals) { + $nbMaxDecimals = static::randomDigit(); + } + + if (null === $max) { + $max = static::randomNumber(); + } + + if ($min > $max) { + $tmp = $min; + $min = $max; + $max = $tmp; + } + + return round($min + mt_rand() / mt_getrandmax() * ($max - $min), $nbMaxDecimals); + } + /** * Returns a random number between $from and $to * diff --git a/test/Faker/Provider/BaseTest.php b/test/Faker/Provider/BaseTest.php index 3feb1278..8a53ad72 100644 --- a/test/Faker/Provider/BaseTest.php +++ b/test/Faker/Provider/BaseTest.php @@ -52,6 +52,22 @@ class BaseTest extends \PHPUnit_Framework_TestCase $this->assertGreaterThanOrEqual(BaseProvider::numberBetween($min, $max), $max); } + public function testRandomFloat() + { + $min = 4; + $max = 10; + $nbMaxDecimals = 8; + + $result = BaseProvider::randomFloat($nbMaxDecimals, $min, $max); + + $parts = explode('.', $result); + + $this->assertInternalType('float', $result); + $this->assertGreaterThanOrEqual($min, $result); + $this->assertLessThanOrEqual($max, $result); + $this->assertLessThanOrEqual($nbMaxDecimals, strlen($parts[1])); + } + public function testRandomLetterReturnsString() { $this->assertTrue(is_string(BaseProvider::randomLetter()));