始终至少显示两位小数

Always display at least two decimal places

本文关键字:两位 小数 显示      更新时间:2024-05-09

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

样品:

1
2.1
123.456
234.45

输出:

1.00
2.10
123.456
234.45

您可以修复为2或当前位置的计数;

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

如何使用Intl:

Intl.NumberFormat(navigator.language, {
  minimumFractionDigits: 2,
  maximumFractionDigits: 10,
}).format(num)

试试这个:

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}$/, ""));

如果你有更多的小数点,你可以很容易地更新数字。