【发布时间】:2015-08-22 13:23:50
【问题描述】:
我有一个随机数生成器函数,它返回一个随机数。看起来问题是有时它只返回一位小数,十分位(我认为它被称为)。我总是希望它输出一个 数字,带有 2 位小数(有时我想要 10.50 时会得到 10.5)。
在我的代码中,我添加了一个加号将其转换为数字。我相信这就是导致百分之一的位置被删除的原因。解决这个问题的最佳方法是什么?
function randomGen() {
return +(Math.random() * 11).toFixed(2)
}
// console.log(randomGen())
// some times i would get 10.5 when i want 10.50
var num1 = randomGen(); // i want 10.50, for example not 10.5
var num2 = randomGen();
console.log(num1, " ", num2)
console.log(+(num1 + num2).toFixed(2))
谢谢
【问题讨论】:
-
randomGen() 函数中的一元运算符没有意义,并且会尝试对该数字进行四舍五入,因此您应该删除它,一切都会好起来的。
标签: javascript random numbers type-conversion