我想格式化我的数字,总是显示2小数点后,四舍五入适用的地方。

例子:

number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35

我一直在用这个:

parseFloat(num).toFixed(2);

但是它把1显示为1,而不是1.00。


当前回答

我喜欢:

var num = 12.749;
parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75

小数四舍五入2位, 然后确保用parseFloat()来解析它 返回Number,而不是String,除非你不在乎它是String还是Number。

其他回答

好消息! ! 似乎javascript的新版本ES2020(我只是使用)提供了这个函数的新行为。

let ff:number =3
console.info(ff.toFixed(2)) //3.00

根据需要。

function currencyFormat (num) {
    return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}

console.info(currencyFormat(2665));   // $2,665.00
console.info(currencyFormat(102665)); // $102,665.00

如果你已经在使用jQuery,你可以看看如何使用jQuery数字格式插件。

该插件可以返回格式化的数字作为字符串,你可以设置小数,和千位分隔符,你可以选择显示的小数的数量。

$.number( 123, 2 ); // Returns '123.00'

你也可以从GitHub获得jQuery数字格式。

一个更通用的N位舍入解决方案

function roundN(num,n){
  return parseFloat(Math.round(num * Math.pow(10, n)) /Math.pow(10,n)).toFixed(n);
}


console.log(roundN(1,2))
console.log(roundN(1.34,2))
console.log(roundN(1.35,2))
console.log(roundN(1.344,2))
console.log(roundN(1.345,2))
console.log(roundN(1.344,3))
console.log(roundN(1.345,3))
console.log(roundN(1.3444,3))
console.log(roundN(1.3455,3))

Output

1.00
1.34
1.35
1.34
1.35
1.344
1.345
1.344
1.346

这里还有一个泛型函数,可以格式化到任何小数位数:

function numberFormat(val, decimalPlaces) {

    var multiplier = Math.pow(10, decimalPlaces);
    return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}