toFixed()that formats a number using fixed-point notation. The
toFixed()method takes one number parameter that tells it how many digits to appear after the decimal point. This number can be a value between
And the method will return a
stringvalue representing the new number generated using fixed-point notation.
Here's an example:
const number = 42.235888
const newNumber = number.toFixed(2)
// newNumber = 42.24
Notice that the
.toFixed(2)method transforms the
42.235888number to a new version with only 2 decimal points.
What happens if you applied the decimal point to a whole number?
Here's a code example for that:
const number = 42
const newNumber = number.toFixed(3)
// newNumber = 42.000
Notice how the new number created by the
.toFixed(3)method has three digits behind the decimal point even though they're zero.
Pretty cool, right?
Let's go over one more example where we want to transform a number with decimal points to a rounded whole number.
Here's the code:
const number = 42.68231
const newNumber = number.toFixed(0)
// newNumber = 43
if you give a value of
.toFixed()method, it will round the new number to a whole number.
Hopefully, this article was helpful in your coding endeavors.
Thanks for reading and happy coding.