Skip to content

RangeError: toFixed() 位数参数必须在 0 到 100 之间

快速摘要

你向 .toFixed 传入了负或过大的精度——只允许 0–100。

为什么发生

  • 精度来自变为负数的计算

  • 从不可信输入传入极大位数

  • 混淆 .toFixed 与限制不同的 .toPrecision

最小示例

✗ 错误代码
const price = 9.99;
console.log(price.toFixed(-2)); // RangeError
✓ 修复代码
const price = 9.99;
const digits = Math.min(100, Math.max(0, -2));
console.log(price.toFixed(digits)); // '10'

负精度对 toFixed 非法。钳制为 0 会回退到无小数位的舍入,避免报错。

如何诊断

  • 阅读指出非法精度的 RangeError

  • 调用前打印精度参数

  • 把精度钳制到合法的 0–100 区间

如何修复

  • 钳制:Math.min(100, Math.max(0, precision))

  • 传入 .toFixed 前校验用户输入

  • 输入越界时使用默认精度

如何预防

  • 调用 .toFixed 前始终校验精度

  • 用常量定义允许的最大精度

相关资源

相关术语

相关课程

← 返回语言