Created
March 29, 2015 06:09
-
-
Save marianogappa/a5a19ae57000a68de9bd to your computer and use it in GitHub Desktop.
Generates a random decimal with a large number of digits.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function big_rand_decimal($integerDigits, $decimalDigits, $decimalSeparator = ".") { | |
if(!is_numeric($integerDigits) || $integerDigits <= 0) | |
$integerDigits = 0; | |
else if(!is_integer($integerDigits)) | |
$integerDigits = (int)ceil($integerDigits); | |
if(!is_numeric($decimalDigits) || $decimalDigits <= 0) | |
$decimalDigits = 0; | |
else if(!is_integer($decimalDigits)) | |
$decimalDigits = (int)ceil($decimalDigits); | |
if($integerDigits + $decimalDigits == 0) | |
return '0' . $decimalSeparator . '0'; | |
$bigInteger = big_rand_integer($integerDigits + $decimalDigits); | |
$bigDecimal = substr($bigInteger, 0, $integerDigits) . $decimalSeparator . substr($bigInteger, $integerDigits); | |
return ($integerDigits == 0 ? '0' : '') . $bigDecimal . ($decimalDigits == 0 ? '0' : ''); | |
} | |
function big_rand_integer($digits) { | |
if(!is_numeric($digits) || $digits <= 0) | |
return '0'; | |
if(!is_integer($digits)) | |
$digits = (int)ceil($digits); | |
$multiplier = (int)ceil($digits / 9.0); | |
$function = function() { | |
return(str_pad(strrev((string)mt_rand()), 9, '0', STR_PAD_LEFT)); | |
}; | |
return substr(str_repeat_func($function, $multiplier), 0, $digits); | |
} | |
function str_repeat_func($function, $multiplier) { | |
if(!is_callable($function) || !is_integer($multiplier) || $multiplier <= 0) | |
return ""; | |
$accumulator = ""; | |
for($i = 0; $i < $multiplier; $i++) | |
$accumulator .= call_user_func($function); | |
return $accumulator; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Returns a string with the decimal. Useful only when the decimal is too complex to be stored within native PHP variables. On extraneous input, it'll return '0.0'; it will always try to give you a valid decimal. If you give it decimal parameters, it'll round them up to the next integers. It uses the mt_rand function internally. It attempts to save cycles by using the 9 useful digits of mt_rand(mt_get_max_rand) instead of calling it once per digit.