DEV Community

Cover image for Exponential Elegance: Rounding Numbers in JS
João Pinho
João Pinho

Posted on

Exponential Elegance: Rounding Numbers in JS

As you may be aware, JavaScript and numbers have unique properties that developers originating from other programming languages should be aware of. You can observe this for yourself: just sum 0.1 + 0.2, and you will see what I mean.

Another common scenario is when developers explicitly define numbers as const rate = 2.0. This was common in Java to avoid integer divisions. In JavaScript, you can still definitely use this convention for readability, but it's not required at all given that all numbers are decimals already.

The point of this post is to introduce another particularity of numbers in JS that may not be well-known, which is the use of the exponential operator.

Let's say you are tasked with implementing a rounding function in JS. As you know, Math.round does not provide precision. So a common pattern is, let's say we want a rounding of 2, we could do:

  • Math.round(1000.230499 * 100) which rounds to 100023
  • Then you divide it by 100 and you get 1000.23

You could easily come up with a generic algorithm that mimics this. But what if I told you that function only takes 5 seconds to write?

  • Number('1000.230499e2') = 100023.0499
  • Number(100023.0499 + 'e-2') = 1000.230499

So a simple rounding function could be:

export const round = (value: number, decimals = 2) => {
  return Number(Math.round(Number(`${value}e${decimals}`)) + `e-${decimals}`);
};
Enter fullscreen mode Exit fullscreen mode

I thought I would share this as it's quite a powerful way to play around with the "comma" in decimals without having to deal with divisions.

Even though AI will do this for you these days, it's always good to know the basics. 👊

[#stayhard] [#keephacking]

Top comments (2)

Collapse
 
artxe2 profile image
Yeom suyun

Why do you declare the function "round" using multiple strings and function calls?
Perhaps the implementation of the function you desire is as follows...

export function round(value, decimals = 2) {
    const n = 10 ** decimals;
    return Math.round(value * n) / n;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jpinho profile image
João Pinho

Why not name it “round”? Why divide vs strings with exponential notation, and using Number native support for floating-point manipulation? 🙂