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

例子:

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

我一直在用这个:

parseFloat(num).toFixed(2);

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


当前回答

你可以试试下面的代码:

    function FormatNumber(number, numberOfDigits = 2) {
        try {
            return new Intl.NumberFormat('en-US').format(parseFloat(number).toFixed(numberOfDigits));
        } catch (error) {
            return 0;
        }
    }

    var test1 = FormatNumber('1000000.4444');
    alert(test1); // 1,000,000.44

    var test2 = FormatNumber(100000000000.55555555, 4);
    alert(test2); // 100,000,000,000.5556

其他回答

用精度方法扩展数学对象

Object.defineProperty(数学、“精度”{ 值:函数(值,精度,类型){ var v = parseFloat(value) p = Math.max(precision,0)||0, T = type||'round'; 返回(数学[t] (v * Math.pow (p)) / Math.pow (p)) .toFixed (p); } }); console.log ( Math.precision(3.1,3), //四舍五入3位 Math.precision(0.12345,2,'ceil'), // ceil 2位数字 Math.precision(1.1) //整数 )

你在找地板吗?

变量数 = 1.42482; var num2 = 1; var fnum = Math.floor(num).toFixed(2); var fnum2 = Math.floor(num2).toFixed(2); console.log(fnum + “ 和 ” + fnum2);两个值均为 1.00

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

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

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

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

(Math.round(num * 100) / 100).toFixed(2);

现场演示

var num1 = “1”; document.getElementById('num1').innerHTML =(Math.round(num1 * 100) / 100).toFixed(2); var num2 = “1.341”; document.getElementById('num2').innerHTML =(Math.round(num2 * 100) / 100).toFixed(2); var num3 = “1.345”; document.getElementById('num3').innerHTML =(Math.round(num3 * 100) / 100).toFixed(2); 跨度 { 边框:1px 实心 #000; 边距:5px; 填充:5px; } <span id=“num1”></span> <span id=“num2”></span> <span id=“num3”></span>

注意,它将四舍五入到小数点后2位,因此输入1.346将返回1.35。

一个更通用的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