Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Number.prototype.toFixed

Formats a number with a given number of decimal places.

Available since: ES3

Syntax

number.toFixed(digits)

Parameters

ParameterTypeDescription
digitsnumberOptional. How many decimal places to keep; 0 by default.

Return value

stringA string holding the rounded number.

Examples

Two decimal places:

console.log((3.14159).toFixed(2));
console.log((2.5).toFixed(2));

Output:

3.14
2.50

The result is a string, not a number:

console.log(typeof (3.14159).toFixed(2));

Output:

string

Notes

Wrap the result in Number() to get a number again. Trailing zeros are lost in the process.

See also

Related recipes

In the tutorial

  • Numbers — Numbers in JavaScript — integers and fractions, rounding, the Math object, toFixed and the special values Infinity and NaN.

Thanks for reading!

Donate to the site — we work hard for you.