始终显示至少两位小数

问题描述:

我想格式化一个数字,使其始终有至少两位小数。始终显示至少两位小数

样品:

1 
2.1 
123.456 
234.45 

输出:

1.00 
2.10 
123.456 
234.45 
+0

结帐http://numeraljs.com/ – adamb

+0

重复http://*.com/questions/6134039/format-number-to-always-show-2-decimal-places –

+3

@DavidBarker您链接的问题需要不管有没有更多,都是2位小数,这不是操作问题。 –

你可以固定到2或当前位置的计;

var result = num.toFixed(Math.max(2, (num.toString().split('.')[1] || []).length)); 

试试这个:

var num = 1.2; 
function decimalPlaces(num) { 
    var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); 
    if (!match) { return 0; } 
    return Math.max(
     0, 
     // Number of digits right of decimal point. 
     (match[1] ? match[1].length : 0) 
     // Adjust for scientific notation. 
     - (match[2] ? +match[2] : 0)); 
} 
if(decimalPlaces(num) < 2){ 
    num = num.toFixed(2); 
} 
alert(num); 

这里是jsfiddle

+1

输出为'1.23',我想'1.2345' – skmasq

+0

请尝试它再次!对不起我的错误。 – HICURIN

尝试这种解决方案(工作),

var a= 1, 
    b= 2.1, 
    c = 123.456, 
    d = 234.45; 

console.log(a.toFixed(4).replace(/0{0,2}$/, "")); 
console.log(b.toFixed(4).replace(/0{0,2}$/, "")); 
console.log(c.toFixed(4).replace(/0{0,2}$/, "")); 
console.log(d.toFixed(4).replace(/0{0,2}$/, "")); 

如果您有更多的小数位,你可以很容易地更新次数。

+0

这是最大4位小数,这不能解决问题。 – skmasq

+0

请参阅答案的最后一行。您可以将其更改为任意数量的小数位,例如。第一个数字是我们可以拥有的最大小数位数(在这种情况下为10),第二个数字是最大数字(最大小数位数是10) -min(在这种情况下为8)。 –

+0

请标记为答案,如果它解决了您的问题。 –