Explain Codes LogoExplain Codes Logo

Format number to always show 2 decimal places

javascript
number-formatting
precision
localization
Alex KataevbyAlex Kataev·Aug 11, 2024
TLDR

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.

const coolNumber = (123.456).toFixed(2); // JavaScript says, "Your wish is my command. Here is your formatted number -> "123.45"

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:

const precisionRound = (number, precision) => { const roundOff = Math.pow(10, precision); return Number(Math.round(number * roundOff) / roundOff).toFixed(precision); }; // Now JavaScript says, "Hold my semicolon... let me do the math for you!" const roundedMaster = precisionRound(1.346, 2); // Wait, what's that sound? It's just JavaScript yelling "Precision! It's gonna be 1.35!"

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."

const truncateNotRound = (number, decimalPlaces) => { const regExMatch = new RegExp(`^-?\\d+(?:.\\d{0,${decimalPlaces}})?`); return number.toString().match(regExMatch)[0]; }; const notRounded = truncateNotRound(1.346, 2); // JavaScript comes back from the council meeting, "They've decided, it's gonna be "1.34""

Special formatting tools in your JavaScript utility belt

Format by locale

Keeping up with the .toLocaleString(), because one size does not fit all:

const number = 123.456; const georgeOrwell = number.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); // JavaScript says, "Your 'en-US' specific formatted number is this -> "123.45""

Grandmaster level: Intl.NumberFormat

Intl.NumberFormat is quite literally... Unlimited Power!

const myNewFancyFormat = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); const aWorldOfPain = myNewFancyFormat.format(123.456); // "123.45" // The crowd goes wild!

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.

document.getElementById('toShow').innerHTML = coolNumber; // Bring out the champagne! "123.45" is now part of your beautiful website.

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!