--- title: Number.prototype.toFixed() slug: Web/JavaScript/Reference/Global_Objects/Number/toFixed tags: - JavaScript - Method - Number - Prototype translation_of: Web/JavaScript/Reference/Global_Objects/Number/toFixed ---
toFixed()
方法會使用定點小數表示法(fixed-point notation)來格式化數字。
numObj.toFixed([digits])
digits 小數位
一個代表以定點小數表示法(fixed-point notation)格式化數字後的字串。
digits
is too small or too large. Values between 0 and 100, inclusive, will not cause a {{jsxref("RangeError")}}. Implementations are allowed to support larger and smaller values as chosen.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 {{jsxref("Number.prototype.toString()")}} and returns a string in exponential notation.
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.23e+20).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 | Status | Comment |
---|---|---|
{{SpecName('ES3')}} | {{Spec2('ES3')}} | Initial definition. Implemented in JavaScript 1.5. |
{{SpecName('ES5.1', '#sec-15.7.4.5', 'Number.prototype.toFixed')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES6', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}} | {{Spec2('ES6')}} | |
{{SpecName('ESDraft', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.builtins.Number.toFixed")}}