php 使用PHP生成两个小数之间的随机小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10419501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:06:32  来源:igfitidea点击:

Use PHP To Generate Random Decimal Beteween Two Decimals

phprandom

提问by Nick Roskam

I need to generate a random number, to the 10th spot between 2 decimals in PHP.

我需要生成一个随机数,到 PHP 中两位小数之间的第 10 位。

Ex. A rand number between 1.2 and 5.7. It would return 3.4

前任。一个介于 1.2 和 5.7 之间的兰特数。它会返回 3.4

How can I do this?

我怎样才能做到这一点?

回答by codaddict

You can use:

您可以使用:

rand ($min*10, $max*10) / 10

or even better:

甚至更好:

mt_rand ($min*10, $max*10) / 10

回答by Deleteman

You could do something like:

你可以这样做:

rand(12, 57) / 10

PHP's random function allows you to only use integer limits, but you can then divide the resulting random number by 10.

PHP 的 random 函数允许您只使用整数限制,但您可以将结果随机数除以 10。

回答by driangle

A more general solution would be:

更通用的解决方案是:

function count_decimals($x){
   return  strlen(substr(strrchr($x+"", "."), 1));
}

public function random($min, $max){
   $decimals = max(count_decimals($min), count_decimals($max));
   $factor = pow(10, $decimals);
   return rand($min*$factor, $max*$factor) / $factor;
}

$answer = random(1.2, 5.7);