toFixed()
方法使用定点表示法来格式化一个数。
numObj.toFixed(digits)
所给数值的定点数表示法的字符串形式。
RangeError
RangeError
。实现环境(implementations)也可以支持更大或更小的值。TypeError
Number
类型的对象上调用。一个数值的字符串表现形式,不使用指数记数法,而是在小数点后有 digits(注:digits具体值取决于传入参数)位数字。该数值在必要时进行四舍五入,另外在必要时会用 0 来填充小数部分,以便小数部分有指定的位数。 如果数值大于 1e+21,该方法会简单调用 Number.prototype.toString()
并返回一个指数记数法格式的字符串。
toFixed
var numObj = 12345.6789;
numObj.toFixed(); // 返回 "12346":进行四舍五入,不包括小数部分
numObj.toFixed(1); // 返回 "12345.7":进行四舍五入
numObj.toFixed(6); // 返回 "12345.678900":用0填充
(1.23e+20).toFixed(2); // 返回 "123000000000000000000.00"
(1.23e-10).toFixed(2); // 返回 "0.00"
2.34.toFixed(1); // 返回 "2.3"
-2.34.toFixed(1); // 返回 -2.3 (由于操作符优先级,负数不会返回字符串)
(-2.34).toFixed(1); // 返回 "-2.3" (若用括号提高优先级,则返回字符串)
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.5. |
ECMAScript 5.1 (ECMA-262) Number.prototype.toFixed |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) Number.prototype.toFixed |
Standard |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
toFixed | Chrome Full support Yes | Edge Full support 12 | Firefox Full support 1 | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Edge Mobile Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support Yes |