Explain Codes LogoExplain Codes Logo

How to format a float in JavaScript?

javascript
tofixed
number-formatting
rounding
Nikita BarsukovbyNikita BarsukovΒ·Aug 14, 2024
⚑TLDR

For instant gratification, use the Number.prototype.toFixed() method:

let num = 123.456; let formattedNum = num.toFixed(2); // "123.46" as String Type

To return it back to a Number:

let numericFormat = parseFloat(formattedNum); // 123.46

Now you can control the precision of your decimals at finger tips πŸ––.

Understanding toFixed()

Using toFixed() handles rounding and limiting decimal points. Check this out:

let x = 2.5; x.toFixed(0); // "3" - rounds off like a bouncy ball x.toFixed(2); // "2.50" - extra zero padding in for the float

To just say no to trailing zeros, use a regular expression with toFixed(), like a combo move:

let cleanValue = x.toFixed(2).replace(/\.?0+$/, ''); // "2.5"

But if rounding is your nemesis, create a custom function:

function preciseRound(value, places) { let power = Math.pow(10, places); return (Math.round(value * power) / power).toString(); }

Advanced ways to round & format

The Maths way

For real control freaks, use Math.round() with Math.pow(). It's like lunar gravity precision:

let closestRound = (num, decimals) => Math.round((num + Number.EPSILON) * Math.pow(10, decimals)) / Math.pow(10, decimals); closestRound(2.005, 2); // 2.01

The friendly human readable version

Create a humanize() function to reduce excess decimals, making it pretty for human eyes πŸ‘€:

function humanize(num) { return +parseFloat(num).toFixed(2); // + operator reverts back to `Number` }

Pitfalls & remedies to be aware of

Dealing with large numbers

For any Hulk sized numbers, toFixed(2) may let you down. But toLocaleString() won't leave you high & dry.

123456.789.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); // "123,456.79"

The quirks of Internet Explorer

If you're stuck with IE, beware its peculiar bugs. Always test your results there. Your future bug-free sleep depends on it.

Binary representation

Because JavaScript uses binary floating-point arithmetics, you might be caught off-guard with rounding errors. For mission-critical tasks, consider looking into libraries like big.js or decimal.js. Hit the problem with the big guns, Bs off.

Alternatives for different use-cases

International-friendly numbers

Use Intl.NumberFormat for different locales, because not everybody uses commas for decimals, right?

new Intl.NumberFormat('en-US', { style: 'decimal', maximumFractionDigits: 2 }).format(num);

More firepower with libraries

Third-party libraries like Numeral.js or accounting.js come handy for more formatting options and locale support.

Honing it down

For tiny numbers

Deal with tiny numbers, switch to Exponential format:

let miniscule = 0.0000123456; miniscule.toExponential(2); // "1.23e-5" - sciency stuff!

Creating prices

For dealing with currency, ensure you have proper formatting:

let cash = 123456.789; cash.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); // "$123,456.79" - cha-ching!