如何从一个函数 return 一个始终保留 2 位小数的数字

how to return a number with 2 decimal places all the time from a function

我有一个随机数生成器函数,它 returns 一个随机数。看起来问题是有时它 returns 只有小数点后一位,十分之一位(我认为它被称为)。我总是希望它输出一个 number2 个小数位(有时我想要 10.50 时会得到 10.5)。

在我的代码中,我放置了一个加号以将其转换为 number.I 相信这就是导致百分之一的位置被删除的原因。解决这个问题的最佳方法是什么?

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)) 

谢谢

去掉 + 号,你应该没问题:

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)) 

如果要将字符串转换为 JavaScript 中的数字,请使用 'parseFloat' 函数。请注意,如果将字符串转换为数字,它将始终截去小数点的零(例如 10.50 变为 10.5)。

使用数字进行计算,得到最终结果后,用'toFixed'方法将其转换为字符串,这样就可以显示两位小数。

in my code i put a plus sign to convert it into a number.I believe this is what is causing the hundredth's place to be deleted. what is the best way to solve this problem?

是 - 不要将其转换为数字!
在数值上,没有 10.50 这样的东西。只有10.5
只有字符串能够保存像 10.50 这样的值,而您 toFixed() 得到 一个字符串,然后将其转换回数字。

所以我说得再好不过了 :

Loose the + signs

使用以下内容:

randomGen(){
   result=(Math.random()*11)
   return parseFloat(result,10).toFixed(2)
    }