Number.prototype.toFixed()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2015å¹´7æ.
toFixed() æ¹æ³æä½¿ç¨å®é»å°æ¸è¡¨ç¤ºæ³ï¼fixed-point notationï¼ä¾æ ¼å¼åæ¸åã
å試ä¸ä¸
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"
èªæ³
numObj.toFixed([digits])
忏
digits å°æ¸ä½-
鏿æ§è¼¸å ¥ã顯示æ¸å¼è³å¤å°åå°æ¸é»ï¼ç¯åç± 0 å° 20 ä¹éï¼å·è¡ææå¯æ¯æ´é常大ç¯åçæ¸å¼ã妿ç¡è¼¸å ¥æé»èªå 0ã
åå³å¼
ä¸å代表以å®é»å°æ¸è¡¨ç¤ºæ³ï¼fixed-point notationï¼æ ¼å¼åæ¸åå¾çå串ã
ä¾å¤
RangeError-
If
digitsis too small or too large. Values between 0 and 100, inclusive, will not cause aRangeError. Implementations are allowed to support larger and smaller values as chosen. TypeError-
If this method is invoked on an object that is not a
Number.
說æ
toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If numObj is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.
ç¯ä¾
>Using toFixed
var numObj = 12345.6789;
numObj.toFixed(); // Returns '12346': note rounding, no fractional part
numObj.toFixed(1); // Returns '12345.7': note rounding
numObj.toFixed(6); // Returns '12345.678900': note added zeros
(1.23e20).toFixed(2); // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2); // Returns '0.00'
(2.34).toFixed(1); // Returns '2.3'
(2.35).toFixed(1); // Returns '2.4'. Note that it rounds up in this case.
-(2.34).toFixed(1); // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1); // Returns '-2.3' (...unless you use parentheses)
è¦ç¯
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-number.prototype.tofixed> |