Prices not aligned properly!!!

Nafis Fuad / December 31, 2020

1 min read ‚ÄĘ ‚Äď‚Äď‚Äď views

Just the other day, while working on a project, it was pointed out that the pricing was not aligned properly. We had to add 2 zeros after the decimal point to make the significant digits stand out, and make the numbers appropriately aligned. So essentially, we wanted to have:

2 => 2.00
0.2 => 0.20

It was clear that we had to do some kind of formatting on the numbers.

We could easily go for a full-blown number formatting library/package like numeral.js, but it wouldn't make sense to add a new dependency and increase the bundle size for such a simple requirement of ours. Hence, here's a handy format function:

const format = (x) => {
    if (!x || typeof x !== 'number') {
        return x // return whatever the value of x is
    }

    const numStr = x.toString() // convert number to string
    const float = Number.parseFloat(numStr) // convert to float
    return float.toFixed(2)
}

Or, a nice and simple one-liner (typescript version) ūüėĪ

const format = (x:number) :number => Number.parseFloat(x.toString()).toFixed(2)

While the one-liner is concise and compact, I went with the verbose one to make sure the util function is clear and readable. Thanks for reading, enjoy! ūüéČ

Subscribe to the boring interesting newsletter

If you enjoy learning new stuff, you should consider joining my newsletter ūüėá. Get emails from me about development ūüĎ©‚ÄćūüíĽ, tech ūü§Ė, and other (un)opinionated matters ūü§ď. My newsletter includes early access to new/upcoming posts and sneak peek into special goodies. No spam ‚õĒ, & you can unsubscribe at any time ūüéČ