JavaScript 中的数字是浮点数。这意味着它们并不总是精确的。
0.3 Bug
0.1 + 0.2 === 0.30000000000000004
永远不要直接比较浮点数。使用 Math.abs(a - b) < epsilon。
处理金钱
对于金钱,使用 Intl.NumberFormat API。它会自动处理逗号、小数和货币符号。
javascript
const price = 12345.678;
const formatter = new Intl.NumberFormat('zh-CN', {
style: 'currency',
currency: 'CNY',
});
console.log(formatter.format(price)); // "¥12,345.68"