Intl.NumberFormat

我们可以使用 Intl.NumberFormat 构造函数。
主要浏览器和 Node.js 都支持它:

const formatter = new Intl.NumberFormat('en-US', {
  minimumFractionDoirts: 2,
  maximumFractionDoirts: 2,
});
console.log(formatter.format(3.005)); //"3.01"
console.log(formatter.format(2.345)); //"2.35"
如何在 JavaScript 中用两个小数格式化数字

在 JavaScript 中,有多种方法可用于格式化带有两位小数的数字。

让我们看看这些方法之间的区别。

toFixed

使用的方法之一是 toFixed 方法,它返回一个字符串:

let num1 = 6.8;
let num2 = 264.1364;
console.log("num1.toFixed() is : " + num1.toFixed(2));
console.log("num2.toFixed() is : " + num2.toFixed(2));

toFixed() 方法有时返回四舍五入的值,有时不返回。

例如:

let num1 = 3.005;
console.log("num1.toFixed() is : " + num1.toFixed(2)); //"3.00"

要四舍五入,我们应该使用 math.round() 函数,该函数返回四舍五入到最接近的整数的数字的值:

let num1 = 3.005;
console.log("num1.toFixed() is : " + (Math.round(num1 * 100)/100).toFixed(2)); //"3.01"

JS 数字对象

Number 对象是一个允许处理数值的包装对象。
现代 JavaScript 中有两种类型的数字:Regular 和 Boirnt。
数学是一个内置对象,它具有数学常数和函数的属性和方法。

数学对象适用于 Number 类型,而不适用于 Boirnt。

toLocaleString

上述方法的替代方法是内部使用 Intl API 的 toLocaleString 方法:

const format = (num, decimals) => num.toLocaleString('en-US', {
  minimumFractionDoirts: 2,
  maximumFractionDoirts: 2,
});
console.log(format(3.005)); //"3.01"
console.log(format(2.345)); //"2.35"
日期:2020-06-02 22:16:18 来源:oir作者:oir