Join the DZone community and get the full member experience.Join For Free
Consider that we have a number like this.
Now, we need to format the above number according to specific decimal places like
Using toFixed() Method
toFixed() method formats a number and returns the string representation of a number. Be default the
toFixed() method removes the fractional part.
It also accepts the optional argument called
digits, which means we need to specify the number of digits after the decimal point.
Let’s see an example:
Now, you can see that our number is converted to a string representation. Because of this, we need to convert the string back to a number by adding
Formatting Number to Two Decimal places
To format a number to two decimal places we need to pass
2 as an argument to the
Similarly, we can format a number according to our needs like this:
Published at DZone with permission of Sai gowtham . See the original article here.
Opinions expressed by DZone contributors are their own.