我是不是遗漏了什么?

var someNumber = 123.456;
someNumber = someNumber.toFixed(2);
alert(typeof(someNumber));
//alerts string

为什么.toFixed()返回一个字符串?

我想把这个数四舍五入到两位十进制数字。


当前回答

可能来不及回答,但您可以将输出与1相乘以再次转换为数字,这里是一个例子。

Const x1 = 1211.1212121; const x2 = x1.toFixed(2)*1; console.log (typeof (x2));

其他回答

你应该像下面这样使用它。

var someNumber: number = 0.000000;
someNumber = Number(someNumber.toFixed(2))

对于像我这样偶然遇到这个古老问题的人,一个现代的解决方案:

const roundValue = (num, decimals = 2) => {
    let scaling = 10 ** decimals;
    return Math.round((num + Number.EPSILON) * scaling) / scaling;
}

裁判:https://stackoverflow.com/a/11832950

当然它会返回一个字符串。如果要对数值变量进行四舍五入,则应该使用Math.round()。toFixed的目的是用固定的小数位数格式化数字,以便显示给用户。

小心使用toFixed()和Math.round(),由于浮点数系统,它们可能会产生意想不到的结果:

function toFixedNumber(num, digits, base){
  var pow = Math.pow(base||10, digits);
  return Math.round(num*pow) / pow;
}

console.log(toFixedNumber(130.795, 2, 10));
// 130.79 (incorrect)
console.log(toFixedNumber(100.795, 2, 10));
// 100.8 

console.log(+130.795.toFixed(2));
// 130.79 (incorrect)
console.log(+100.795.toFixed(2));
// 100.8

我建议使用Lodash的_.round()函数:https://lodash.com/docs/4.17.15#round

_.round(130.795, 2);
// 130.8

当它格式化一个数字时,你期望它返回什么?如果你有一个数字,你几乎不能对它做任何事情,因为例如2 == 2.0 == 2.00等,所以它必须是一个字符串。