6

I'm wondering if there is a way to make large numbers readable in JavaScript. I'm sure there is I just can't find it. For example, if I am writing

for (var i=0; i < 1000000; i++){
codecodecode};

is there a way to write that 1000000 so that it's readable without disrupting the for loop?

Furthermore, is there a way of returning a large number so that, too, is readable?

Sorry if I explained this poorly, I'm just starting out...

Thanks in advance!

Kelly Hall
  • 71
  • 1
  • 3
  • 1
    What exactly do you mean by "readable"? – Pointy Jul 11 '13 at 23:52
  • perhaps a nearby comment would help. For example, above your loop, you could write `// for i = 0 to 1,000,000` so that you could see what's going on more easily. Other than the answer below, there is no other way to type out numerics – wlyles Jul 11 '13 at 23:59
  • For formatted output, consider the answers here: [*How to print a number with commas as thousands separators in JavaScript*](http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript). – RobG Jul 11 '13 at 23:59
  • `10**6` - 10 in the power of 6 = `1000000` – vsync May 17 '20 at 08:09

3 Answers3

8

Add underscore

100_000_000_000

const loopCount = 50_000

for (var i=0; i < 1_000_000; i++){ codecodecode};

for more information go here (https://2ality.com/2018/02/numeric-separators.html)

Omer
  • 3,232
  • 1
  • 19
  • 19
  • This does not work on its own. The JS Numeric Separator requires adding `@babel/plugin-proposal-numeric-separator` to the list of plugins. – mrmicrowaveoven Jul 14 '21 at 17:30
6

If you are thinking about the source code, you can write 1E6. You are looking for some symbol to seperate the thousands, but unfortunately there is no way.

If you want to convert a number to a more readable string, then this SO post may help you.

Community
  • 1
  • 1
apartridge
  • 1,790
  • 11
  • 18
1

Try this:

    let humanRead = (num,intSep = ',',floatSep = '.') => {

 return new Intl
    .NumberFormat('en-US')
    .format(num)
    .replaceAll('.',floatSep)
    .replaceAll(',',intSep);

}




console.log(humanRead(233234434.23))
    console.log(humanRead(233234434.23,'_'))
    console.log(humanRead(233234434.23,'_','@'))
    console.log(humanRead('') )
    console.log(humanRead('string'))
    console.log(humanRead('st2in9') )
    console.log(humanRead(NaN))
    console.log(humanRead(undefined))