简体   繁体   中英

How to convert a very large decimal number to a string?

I want to convert the decimal number 123.456e+304 to the string "123.456e+304" (the position of the decimal point . should not be changed).

Here is what I've tried, but all of them return the same result: 1.23456e+306 (the position of the decimal point has been changed, and it has also replaced 304 with 306 ).

 var e = 123.456e+304; console.log(e.toString()); console.log((e).toString()); console.log(e .toString()); console.log(e.toFixed()); console.log(String(e)); console.log((new String(e)).toString()); console.log(`${e}`); console.log('' + e); console.log(e + ''); console.log(''.split.call(e, '').join(''));

Is there any way to convert it to the expect string "123.456e+304" ?

It is not possible, because once you assigned:

var e = 123.456e+304;

and is processed by the JavaScript interpreter, e is just a number internally represented by IEEE 754 a number equivalent to 1.23456e+306 and it has "no memory" where your decimal point was. So no matter what you do, you can't know where the decimal point was and let you move it to where you want it to be in a string.

In order "to have the knowledge" of where the decimal point was, you need to have a string to begin with, but that's also the result that you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM