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

add Random Float method

This commit is contained in:
Charles SANQUER 2013-02-20 14:59:46 +01:00
parent e1df66d090
commit 6e563b81cc
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()));