0

Is there a way to make a large number, i.e. 1000000, more readable in JS code?

I know in Ruby you can write 1_000_000 instead, which makes it a lot easier to identify visually.

Thanks.

fafafariba
  • 335
  • 1
  • 2
  • 12

4 Answers4

2

I generally use multiplication in this situation; in this case I'd use 1000 * 1000. Other examples

one megabytes is 1000 * 1024
one hour (in milliseconds) is 60 * 60 * 1000

etc. This isn't quite as nice as the underscore notation, but on the other hand, it requires no special language support.

Another approach is to define "constants", for example:

var ONE_MILLION = 1000000;

or combining the two:

var ONE_MILLION = 1000 * 1000;
jdigital
  • 11,926
  • 4
  • 34
  • 51
1

You cannot use underscores or commas, however, you can use exponential notation:

var million = 1e6;
// Works for small numbers too.
var millionth = 1e-6;
Kyle Lin
  • 827
  • 8
  • 16
1

Nowadays numeric separators are already shipping in chrome 75 and can be transpiler for other browsers. Take a look on the exemple:

1_000_000_000_000 // the same of 1000000000000
1_019_020_900.42 // the same of 1019020900.42
Ênio Abrantes
  • 302
  • 2
  • 11
0

Another option you could do is write a function that takes a number as a string and returns the number. I personally wouldn't do it this way, because it seems tedious and overcomplicated for no real gain. But hey, it's an option!

function n(stringNum){
   // some code that I don't want to write right now.
}

var fooBar = n("1,000,000");
// fooBar = 1000000
tyler mackenzie
  • 622
  • 7
  • 18