Explain Codes LogoExplain Codes Logo

Javascript displaying a float to 2 decimal places

javascript
prompt-engineering
functions
best-practices
Alex KataevbyAlex Kataev·Oct 16, 2024
TLDR

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:

const number = 123.456; //-rounds off those rough edges to keep it at 2 places like a decorous gentleman. const formatted = number.toFixed(2); // "123.46"

However, to get a numerical value back, you can parse the result:

//Float like a butterfly, sting like parseFloat! const numericFormatted = parseFloat(formatted); // 123.46

“But I want a number without trailing zeros.” Sir Unary Plus to the rescue:

//Behold! The Great Unary Plus! const cleanNumber = +formatted; // 123.46

Or, for a more primal solution without the hubbub of string conversion, make friends with multiply and divide:

// DIY rounding, coz why not? const roundedNumber = Math.round(number * 100) / 100; // 123.46

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:

//Keeping integers free from decimal chains. You Float? You get the '.toFixed'! const formatIfFloat = (num) => num % 1 ? num.toFixed(2) : String(num);

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:

const price = 9.99; const quantity = 3; //Precise arithmetic, because every cent counts! let total = +(price * quantity).toFixed(2);

Jazz it up with some locale

Want to format a number based on local customs? toLocaleString() hears you:

//When in Rome, format as the Romans do! const localized = number.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});

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!