Explain Codes LogoExplain Codes Logo

Formatting a number with exactly two decimals in JavaScript

javascript
number-formatting
decimal-precision
javascript-functions
Alex KataevbyAlex Kataev·Oct 7, 2024
TLDR

Use toFixed(2) to format a number to two decimal places in JavaScript.

const formatted = (123.456).toFixed(2); // "123.46" - That's pretty neat!

Beware that toFixed() isn't just the king of rounding, it's also a shape-shifter, changing your number into a string!

Rounding Out the Basics

Let's start with your common garden-variety rounding techniques in JavaScript:

Rounding with toFixed()

toFixed() method by itself can get you there.

let num = 12.34567; let rounded = num.toFixed(2); console.log(rounded); // Prints: "12.35" - Ah, Rounded and well-shaped!

Better watch out though, because the toFixed method will always return a string. You need to convert it back to a number if you need it for further calculations.

Rounding with Precision

Remember, Rounding numbers is like telling a joke; accuracy matters. For better precision, consider this:

function precise_round(num, decimals) { var sign = num >= 0 ? 1 : -1; num = Math.abs(num); return (Math.round((num * Math.pow(10, decimals)) + (sign * 0.0001)) / Math.pow(10, decimals)).toFixed(decimals); } // Because numbers too have feelings; they want precise rounding.

The sign ensures that we round correctly for negative numbers too.

International Number Formatting

When numbers go global, they need to dress accordingly. Use Intl.NumberFormat. This formats numbers according to different locales.

var formatted = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(12.3456789); console.log(formatted); // Prints: "12.35", because in America, we like precision.

Using Intl.NumberFormat, we maintain precision while also getting nicely formatted output!

Life is full of surprises; so is rounding in JavaScript. Some edge cases to be aware of:

Alternative Rounding Method (Math.round)

By using Math.round and some simple arithmetic, we can side-step some of the quirks with toFixed.

This function is a multi-talented performer, not only performs rounding but multiplies and divides too! Talk about multi-tasking!

function alternativeRounding(num) { return (Math.round(num * 100) / 100).toFixed(2); } // Who knew rounding numbers could be such a "roundabout" process!

This dodges some of the weirdness with floating-point numbers.

Going Beyond Basics

For those who want more, here's a journey to the deep end of the pool:

Importance of Performance

When it comes to banking operations or high-frequency computations, performance matters! Be sure to consider the impact of different rounding and formatting methods in terms of performance.

Variable Decimal Places

Sometimes, life doesn't simply revolve around two decimal places. For those situations:

function dynamicPrecisionRounding(num, precision) { const factor = Math.pow(10, precision); return (Math.round(num * factor) / factor).toFixed(precision); } // Because why should "two" have all the fun!

This conveniently supports different decimal lengths without tweaking your code.