简体   繁体   English

始终至少显示两位小数

[英]Always display at least two decimal places

I want to format a number so that it always have at least two decimal places.我想格式化一个数字,使其始终至少有两个小数位。

Samples:样品:

1
2.1
123.456
234.45

Output:输出:

1.00
2.10
123.456
234.45

您可以固定为 2 或当前位置的数量;

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

How about using Intl :如何使用Intl

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

Try this:试试这个:

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);

Here is jsfiddle这是jsfiddle

Try this solution (working),试试这个解决方案(工作),

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

If you have more decimal places, you can updated the number easily.如果您有更多小数位,则可以轻松更新数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM