{{JSRef("Global_Objects", "Number")}}
Summary
The toFixed()
method formats a number using fixed-point notation.
Syntax
numObj.toFixed(digits)
Parameter
- digits
- The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.
Returns
A string representation of number
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 number
is greater than 1e+21, this method simply calls
{{jsxref("Global_Objects/Number/toString", "Number.prototype.toString()")}}
and returns a string in exponential notation.
Throws
- {{jsxref("Global_Objects/RangeError", "RangeError")}}
-
If digits is too small or too large. Values between 0 and 20, inclusive, will not cause a
RangeError
. Implementations are allowed to support larger and smaller values as well.
- {{jsxref("Global_Objects/TypeError", "TypeError")}}
-
If this method is invoked on an object that is not a
Number
.
Examples
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.34.toFixed(1); // Returns -2.3 (due to operator precedence, negative numbers don't return a string...) (-2.34).toFixed(1); // Returns "-2.3" (...unless you use parentheses)
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition. Implemented in JavaScript 1.5 | Standard | Initial definition. |
{{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')}} |
Browser compatibility
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |
See Also
- {{jsxref("Number.prototype.toExponential()")}}
- {{jsxref("Number.prototype.toPrecision()")}}
- {{jsxref("Number.prototype.toString()")}}