在Javascript中生成一个介于2个值到2个小数位之间的随机数 [英] Generate a Random Number between 2 values to 2 decimals places in Javascript
问题描述
我想生成一个1到10之间的随机数,最多2个小数位,
I want to generate a random number between 1 and 10 up to 2 decimal places,
我目前正在下面使用它来生成我的电话号码,
I'm currently using this below to generate my numbers,
var randomnum = Math.floor(Math.random() * (10.00 - 1.00 + 1.00)) + 1.00;
最终,我想知道如何生成数字:
Ultimately, I would like to know how to generate numbers like:
1.66
5.86
8.34
采用以下格式: var randomnum = 然后输入代码
In the format: var randomnum = then the code
边注:我不记得为什么以前要生成这样的数字,但记得有关 Math.random 生成数字到小数点后8位的事情.
sidenote: I don't remember why I previously had generated my numbers like that but remember something about Math.random generating numbers to 8 decimal places.
谢谢您的帮助! :)
Ps:我见过很多关于等待四舍五入或四舍五入生成数字的帖子,却没有找到想要直接生成它们的帖子.
Ps: I've seen a lot of posts about waiting to round down or up generated numbers and haven't found one wanting to generate them straight out.
更新:我希望数字值不是看起来像数字的字符串
UPDATE: I want a number value not a string that looks like a number
推荐答案
您非常接近,您不需要使用最小和最大十进制数.假设max = 1000,min = 100,因此在Math.floor之后,您需要除以100:
You were very close, what you need is not to work with decimal numbers as min and max. Let's have max = 1000 and min = 100, so after your Math.floor you will need to divide by 100:
var randomnum = Math.floor(Math.random() * (1000 - 100) + 100) / 100;
或者如果您想使用小数:
Or if you want to work with decimals:
var precision = 100; // 2 decimals
var randomnum = Math.floor(Math.random() * (10 * precision - 1 * precision) + 1 * precision) / (1*precision);
这篇关于在Javascript中生成一个介于2个值到2个小数位之间的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!