始终显示至少两位小数
你可以固定到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
尝试这种解决方案(工作),
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}$/, ""));
如果您有更多的小数位,你可以很容易地更新次数。
这是最大4位小数,这不能解决问题。 – skmasq
请参阅答案的最后一行。您可以将其更改为任意数量的小数位,例如。第一个数字是我们可以拥有的最大小数位数(在这种情况下为10),第二个数字是最大数字(最大小数位数是10) -min(在这种情况下为8)。 –
请标记为答案,如果它解决了您的问题。 –
结帐http://numeraljs.com/ – adamb
重复http://*.com/questions/6134039/format-number-to-always-show-2-decimal-places –
@DavidBarker您链接的问题需要不管有没有更多,都是2位小数,这不是操作问题。 –