This content originally appeared on Go Make Things and was authored by Go Make Things
Let’s imagine you have a number, pi
, with five decimal places.
let pi = 3.14159;
You want to display with only two. How would you do that?
The Number.toFixed()
method formats a number to a fixed number of decimal places. Call it on the number, and pass in the number of decimal places as an argument.
It returns a formatted string.
let pi = 3.14159;
// returns "3.14"
pi.toFixed(2);
If you call the Number.toFixed()
method on a number that has fewer decimal places than the number specified, 0’s will be added.
let eleven = 11;
// returns "11.000"
eleven.toFixed(3);
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2021-06-09T14:30:00+00:00) How to format a number to a fixed number of decimal places with vanilla JS. Retrieved from https://www.scien.cx/2021/06/09/how-to-format-a-number-to-a-fixed-number-of-decimal-places-with-vanilla-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.