最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Making large numbers readable in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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!

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!

Share Improve this question asked Jul 11, 2013 at 23:51 Kelly HallKelly Hall 711 silver badge3 bronze badges 4
  • 1 What exactly do you mean by "readable"? – Pointy Commented Jul 11, 2013 at 23:52
  • perhaps a nearby ment 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 Commented Jul 11, 2013 at 23:59
  • For formatted output, consider the answers here: How to print a number with mas as thousands separators in JavaScript. – RobG Commented Jul 11, 2013 at 23:59
  • 10**6 - 10 in the power of 6 = 1000000 – vsync Commented May 17, 2020 at 8:09
Add a ment  | 

3 Answers 3

Reset to default 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./2018/02/numeric-separators.html)

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.

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))

发布评论

评论列表(0)

  1. 暂无评论