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

例子:

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

我一直在用这个:

parseFloat(num).toFixed(2);

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


当前回答

(num + "").replace(/^([0-9]*)(\.[0-9]{1,2})?.*$/,"$1$2")

其他回答

我喜欢:

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

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

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

为了获得最精确的舍入,创建这个函数并使用它舍入到小数点后2位:

功能轮(价值,十进制)( return编号(数学。(价值+ e +十进制)+ e-' +十进制)。 ) log(“seeked to”+ round(1,005,2));

> 1.01

感谢Razu、这篇文章和MDN的数学。圆的参考。

RegExp -替代方法

在输入时,你有字符串(因为你使用解析),所以我们可以通过只使用字符串操作和整数计算得到结果

let toFix2 = (n) = > n.replace (d / \(?) -(+)。\ \ \ \ d (d + 1) / (_), s, i、d (r) = {> 让k= (+r[0]>=5)+ +d - (r==5 && s=='-'); 返回s +(+i+(k>99)) + "。"(k +(> 99%) ? ? 9: 00”(k≥0 " k " + k)); }) / /测试 console.log toFix2(“1”)); console.log (toFix2 1.341”()); console.log (toFix2 1.345”()); console.log (toFix2 1.005”());

解释

s is sign, i is integer part, d are first two digits after dot, r are other digits (we use r[0] value to calc rounding) k contains information about last two digits (represented as integer number) if r[0] is >=5 then we add 1 to d - but in case when we have minus number (s=='-') and r is exact equal to 5 then in this case we substract 1 (for compatibility reasons - in same way Math.round works for minus numbers e.g Math.round(-1.5)==-1) after that if last two digits k are greater than 99 then we add one to integer part i

这里有另一个只使用底价的四舍五入的解决方案,这意味着,确保计算的金额不会大于原始金额(有时交易需要):

Math.floor(num* 100 )/100;