The
Number.toFixed()
method returns a value with the specified number of decimal places.
Description
The
toFixed()
method from JavaScript’s
Number
object lets you change numbers into strings with a specific number of decimal places. Use
parseFloat
to convert the result back into a number, see example.
Parameters
Number
— The number of decimal places you want in your output string.
Return Type
A
String
Examples
// Sample JavaScript
const myNumber = 1.5;
// All of these return a string NOT a number
myNumber.toFixed(0); // 2 — Rounds up
myNumber.toFixed(1); // 1.5
myNumber.toFixed(2); // 1.50 — Padded with 0s
myNumber.toFixed(1.4); // 1 — Rounds down
How do I convert it back to a Number?
It’s simple! Just use the
parseFloat()
method.
// Sample JavaScript
const myNumber = 1.5;
// These all return a number
parseFloat( myNumber.toFixed(0) ); // 2 — Rounds up
parseFloat( myNumber.toFixed(1) ); // 1.5
See Also
- Math.round()— Returns a value rounded to the nearest whole number.
- Number.toPrecision()— Returns a value to specified number of significant digits.
Additional Notes
Maybe a quick warning about math in JS and conversion losing precision.
Full Developer Reference
Attribution
- "Original Content" by Mozilla Contributors, licensed under CC-BY-SA 2.5 | Modified from the Original