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.EPSILO...