Skip to content

toFixed 返回字符串而非数字

快速摘要

你写了 price.toFixed(2) + shipping——toFixed 返回字符串,于是 + 拼接而非相加。

为什么发生

  • 把 .toFixed 的结果用于后续算术

  • 把 toFixed 输出赋给类型为 number 的变量

  • 把 .toFixed 与字符串上不存在的数字方法链式调用

最小示例

✗ 错误代码
const price = 9.99;
const shipping = 5;
const total = price.toFixed(2) + shipping; // '9.995' — concatenation!
console.log(total);
✓ 修复代码
const price = 9.99;
const shipping = 5;
const total = (price + shipping).toFixed(2); // '14.99'
console.log(total);

toFixed 返回字符串,与数字相加会拼接。先做算术、最后调用 toFixed 可得到正确数字总额并格式化为字符串。

如何诊断

  • 检查 .toFixed 后值的 typeof——它是 'string'

  • 打印表达式结果以发现 '9.995' 之类的拼接

  • 查找流入数字运算的 .toFixed 结果

如何修复

  • 需要数字时用 Number(price.toFixed(2)) 转回

  • 所有算术在调用 .toFixed 前完成,仅在显示时调用

  • 金额运算用返回数字的十进制库

如何预防

  • 仅在最终显示步骤调用 .toFixed,绝不中途调用

  • 用 TypeScript 标记被当作数字的字符串结果

相关资源

相关术语

相关课程

← 返回语言