DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

6 3

Underscores as number separators

Making calculations with longer numbers? You can improve readability by using underscores (_) in numeric primitives:

// Hard to read:
Math.floor(Math.random() * 1000000); // 337083

// Better
Math.floor(Math.random() * 1_000_000); // 337083

1_000_000 === 1000000 // true
Enter fullscreen mode Exit fullscreen mode

The underscore doesn't have to be placed where a comma would go - it can be used anywhere in the number except at the very beginning or end. Just a small way to improve your code and prevent errors!


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

Top comments (2)

Collapse
 
jankapunkt profile image
Jan Küster 🔥

How so you feel about the choice of the _ as separator?

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak

I guess it was a good neutral choice. Because many languages use many very different separators: commas, dots, spaces, ...

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay