Format number to always show 2 decimal places
Want two decimal places in JavaScript? Here's a quick run. Use toFixed(2)
on a number. It's as simple as pie that rounds if necessary and pads with zeros otherwise. Remember, the result is a string, not a number anymore.
Checkmate! Your number is now always presented as a String with two decimal digits trailing the decimal point.
When (and why) to go beyond toFixed(2)
Danaerys said: "I don't want to stop the wheel. I want to break the wheel."
toFixed()
is cool, but not always the full solution. Here's more.
Accurate and bulletproof rounding
Around decimals, float arithmetic can turn into a gremlin! Wrangle it using the equation of rounding to the rescue:
But what about truncation, you ask?
Precision truncation: No rounding!
For this operation JavaScript is like, "The council has made a decision to only truncate, but given that it's a stupid decision, I've elected to ignore it."
Special formatting tools in your JavaScript utility belt
Format by locale
Keeping up with the .toLocaleString()
, because one size does not fit all:
Grandmaster level: Intl.NumberFormat
Intl.NumberFormat
is quite literally... Unlimited Power!
Always remember, with great NumberFormat
power, comes great localization responsibility.
The tri-factor: implement, present, and stay informed
Show it off on HTML
Basking in the glory of our beautifully formatted numbers, by displaying them using our good old friend, innerHTML
.
The conclave of reusable functions
To avoid coder's fatigue, save your wrists and make reusable functions. Let the functions do their parts, while you sit back and enjoy the show.
Staying updated
New standard? No problem. Keep an eye out for new and improved ways of tackling number formatting. JavaScript ain't stopping, and neither can you!
Was this article helpful?