13

Some languages, like Java and C++, allow you to use numeric separators. To improve readability, you can group digits per thousand:

1_000_000_000

But not only per thousand; you can use it anywhere really. Say you have some value in centimeters. Separating it like this makes it easier for humans to read it as meters:

10_00  // 10 meters

Isn't there any way to accomplish this in JavaScript?

2

3 Answers 3

22

This feature is now added as part of ES2021.

And it works for any numeric base:

const decimal = 1_234;
const binary = 0b1000_0101;
const hex = 0x12_34_56_78;

It is supported by all major browsers (Chrome, Firefox, Edge, Safari, Opera) (source 1, source 2). And if you're working on the server side, Node.js v12.5.0 is already supporting it. Electron too.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm trying to make this work with my app but I'm getting a Failed to compile error. I'm using ecma version 2018. What am I missing?
@MixMasterMike this is not part of ECMAScript 2018 (not even 2019). It is a stage 3 proposal, not yet ready for release. I edited my answer to add that info. You will only be able to get this feature via v8 and projects that use it (Chrome, Nodejs, Electron, etc). Whatever the platform you're using, be sure to check if it uses at least v8 7.5. Well, it looks like Babel also supports it (see other answer).
1

It sounds interesting. I found this worked on the latest version of Chrome.

Babel also supports it in stage-0. Then you can use Babel to transpile to ECMAScript 2015 (ES6).

Try it on Babel.

Comments

0

Constants are better for reading in some cases:

const G = 1**9;
const M = 1**6;
const k = 1**3;
const cm = 0.01;

var size = 5 * G;
var count = 10 * k;
var length = 100 * cm;

1 Comment

I like that, but it would be powers of 10, not 1: const M = 10**6;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.