1
0
mirror of https://github.com/fzaninotto/Faker.git synced 2025-03-22 00:09:59 +01:00

Merge pull request #116 from csanquer/feature_random_float

add Random Float method
This commit is contained in:
Francois Zaninotto 2013-02-20 08:49:53 -08:00
commit 5d0abf6d62
3 changed files with 47 additions and 0 deletions

View File

@ -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'

View File

@ -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
*

View File

@ -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()));