javascript 获取 0.0200 到 0.120 之间的随机数(浮点数)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17726753/
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
Get a random number between 0.0200 and 0.120 (float numbers)
提问by danieljames
I need to create a random number between 0.0200 and 0.120 using JavaScript. How would I do this?
我需要使用 JavaScript 创建一个介于 0.0200 和 0.120 之间的随机数。我该怎么做?
回答by Alesanco
You could use
你可以用
(Math.random() * (0.120 - 0.0200) + 0.0200).toFixed(4)
toFixed(n) is used to convert a number into a string, keeping only the "n" decimals.
toFixed(n) 用于将数字转换为字符串,仅保留“n”个小数。
Hope it helps ^_^
希望对你有帮助^_^
回答by Guilherme Oderdenge
Here you are:
这个给你:
function generateRandomNumber() {
var min = 0.0200,
max = 0.120,
highlightedNumber = Math.random() * (max - min) + min;
alert(highlightedNumber);
};
generateRandomNumber();
I understand your real question — you do not know how to get a random number between floating numbers, right? By the way, the answer is passed before.
我理解你真正的问题——你不知道如何在浮点数之间得到一个随机数,对吧?顺便说一句,答案之前已经通过了。
To play with the code, just click here to jsFiddle.
要使用代码,只需单击此处到 jsFiddle。
Update
更新
To get the four first numbers of your decimal, use .toFixed(3)
method. I've performed an example here, on jsFiddle.
要获得小数的前四个数字,请使用.toFixed(3)
方法。我在 jsFiddle 上做了一个例子。
回答by Victor Quinn
If you're looking to generate that and other random numbers or things, I'd suggest taking a look the Chancelibrary. It provides a nice abstraction layer so you don't have to fiddle with Math.random() and write your own.
如果您想生成那个和其他随机数或东西,我建议您查看Chance库。它提供了一个很好的抽象层,因此您不必摆弄 Math.random() 并编写自己的抽象层。
chance.floating({min: 0.02, max: 0.12});
Full disclosure: I'm the author so I'm a bit biased :)
完全披露:我是作者,所以我有点偏见:)
Also, if this is the only random thing you need to generate or it's client-side where size is a real issue, I'd suggest just using one of the suggestions above. Not worth a few Kb where a couple lines will do.
此外,如果这是您需要生成的唯一随机内容,或者它是客户端的大小是一个真正的问题,我建议只使用上述建议之一。不值几 Kb,几行就行。