How to avoid scientific notation for large numbers in JavaScript?

后端 未结 22 2044
無奈伤痛
無奈伤痛 2020-11-22 00:31

JavaScript converts a large INT to scientific notation when the number becomes large. How can I prevent this from happening?

22条回答
  •  长情又很酷
    2020-11-22 00:56

    I know this is an older question, but shows recently active. MDN toLocaleString

    const myNumb = 1000000000000000000000;
    console.log( myNumb ); // 1e+21
    console.log( myNumb.toLocaleString() ); // "1,000,000,000,000,000,000,000"
    console.log( myNumb.toLocaleString('fullwide', {useGrouping:false}) ); // "1000000000000000000000"
    

    you can use options to format the output.

    Note:

    Number.toLocaleString() rounds after 16 decimal places, so that...

    const myNumb = 586084736227728377283728272309128120398;
    console.log( myNumb.toLocaleString('fullwide', { useGrouping: false }) );
    

    ...returns...

    586084736227728400000000000000000000000

    This is perhaps undesirable if accuracy is important in the intended result.

提交回复
热议问题