Javascript displaying a float to 2 decimal places
To display a float with two decimal places in JavaScript, use toFixed(2)
. This handy method creates a string representation of the float rounded to two decimals:
However, to get a numerical value back, you can parse the result:
“But I want a number without trailing zeros.” Sir Unary Plus to the rescue:
Or, for a more primal solution without the hubbub of string conversion, make friends with multiply and divide:
Quick tour to edge cases
toFixed(2)
shine
toFixed(2)
is your magic charm to get an exact number of decimal places, perfect for most applications, especially when dealing with monetary values. Just keep in mind it returns a string.
Trailing zeros, the uninvited guest
If you don't want floating-point decimals for your integer values, conditional use of toFixed(2)
can show them the exit door:
Old IE, the party pooper
If you're one of the superheroes supporting older versions of IE, beware toFixed()
has some history. Karma of the past, huh? Also test thoroughly.
Have a blind date with toPrecision(2)
toPrecision(2)
might seduce you with its charm, but is unreliable. It tends to whimsically round numbers like 0.05 to 0.050
, catastrophic when minimizing decimals.
Beyond toFixed()
When toFixed()
is too mainstream, look out for custom formatting functions or libraries like Numeral.js
or accounting.js
.
An alert to money handlers
For handling currency, being defensive is a strength. Don't just focus on displaying numbers, make sure you calculate with precision. Floating-point arithmetic issues can be a sly fox:
Jazz it up with some locale
Want to format a number based on local customs? toLocaleString()
hears you:
Turbocharge your code
While toFixed(2)
is easy, in high-performance code, math-based rounding or lookup tables might win the race. And don't forget to profile your code, coz after all, the proof of the pudding is in the eating!
Was this article helpful?