Number.prototype.toFixed()
试一试
function financial(x) {
return Number.parseFloat(x).toFixed(2);
}
console.log(financial(123.456));
// Expected output: "123.46"
console.log(financial(0.004));
// Expected output: "0.00"
console.log(financial("1.23e+5"));
// Expected output: "123000.00"
语法
js
toFixed()
toFixed(digits)
参数
digits可选-
小数点后要显示的数字位数;值应介于
0和100之间(含)。如果省略此参数,则视为0。
返回值
一个字符串,表示给定数字的定点表示法。当数字的绝对值大于或等于 1021 时,会使用科学记数法(返回值与 Number.prototype.toString() 相同)。
异常
RangeError-
如果
digits不在0和100之间(含),则抛出错误。 TypeError-
如果此方法在非
Number对象上调用,则抛出该错误。
描述
toFixed() 方法返回一个不使用 指数记数法 且小数点后恰好有 digits 位数字的数字的字符串表示形式。如果需要,数字会被四舍五入,如果需要,小数部分会用零填充,使其具有指定的长度。
如果数字的绝对值大于或等于 1021,则此方法使用与 Number.prototype.toString() 相同的算法,并返回一个指数记数法的字符串。如果数字的值是无限的,toFixed() 会返回 "Infinity"、"NaN" 或 "-Infinity"。
对于某些值,toFixed() 的输出可能比 toString() 更精确,因为 toString() 只会输出足够的有效数字来区分该数字与其他相邻的数字值。例如:
js
(1000000000000000128).toString(); // '1000000000000000100'
(1000000000000000128).toFixed(0); // '1000000000000000128'
但是,选择过高的 digits 精度可能会返回意外结果,因为十进制分数不能在浮点数中精确表示。例如:
js
(0.3).toFixed(50); // '0.29999999999999998889776975374843459576368331909180'
示例
使用 toFixed()
js
const numObj = 12345.6789;
numObj.toFixed(); // '12346'; rounding, no fractional part
numObj.toFixed(1); // '12345.7'; it rounds up
numObj.toFixed(6); // '12345.678900'; additional zeros
(1.23e20).toFixed(2); // '123000000000000000000.00'
(1.23e-10).toFixed(2); // '0.00'
(2.34).toFixed(1); // '2.3'
(2.35).toFixed(1); // '2.4'; it rounds up
(2.55).toFixed(1); // '2.5'
// it rounds down as it can't be represented exactly by a float and the
// closest representable float is lower
(2.449999999999999999).toFixed(1); // '2.5'
// it rounds up as it's less than Number.EPSILON away from 2.45.
// This literal actually encodes the same number value as 2.45
(6.02 * 10 ** 23).toFixed(50); // '6.019999999999999e+23'; large numbers still use exponential notation
使用 toFixed() 处理负数
由于成员访问的 优先级 高于一元减号,因此您需要对负数表达式进行分组才能得到字符串。
js
-2.34.toFixed(1); // -2.3; a number
(-2.34).toFixed(1); // '-2.3'
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-number.prototype.tofixed |
浏览器兼容性
加载中…