JavaScript 保留两位小数的方法

在 JavaScript 中有多种方法可以将数字保留两位小数,以下是几种常用的方法:

1. 使用 toFixed() 方法

let num = 123.45678;
let result = num.toFixed(2); // "123.46" (返回的是字符串)

注意:toFixed() 返回的是字符串,如果需要数字可以再转换:

let numResult = parseFloat(num.toFixed(2)); // 123.46 (数字)

2. 使用 Math.round() 方法

let num = 123.45678;
let result = Math.round(num * 100) / 100; // 123.46 (数字)

3. 使用 Number.EPSILON 避免舍入误差

let num = 123.45678;
let result = Math.round((num + Number.EPSILON) * 100) / 100; // 123.46

4. 使用 Intl.NumberFormat (支持本地化)

let num = 123.45678;
let formatter = new Intl.NumberFormat('en-US', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
let result = formatter.format(num); // "123.46" (字符串)

5. 自定义函数

function roundToTwo(num) {
  return +(Math.round(num + "e+2") + "e-2");
}

let result = roundToTwo(123.45678); // 123.46

注意事项

  1. 浮点数运算可能存在精度问题,如 0.1 + 0.2 !== 0.3

  2. 对于货币计算等需要高精度的场景,建议使用专门的库如 decimal.js

  3. toFixed() 会进行四舍五入,但有时会有意外的舍入结果

选择哪种方法取决于你的具体需求,如是否需要返回字符串或数字,是否需要考虑本地化等。