Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

integer - Javascript parsing int64

How can I convert a long integer (as a string) to a numerical format in Javascript without javascript rounding it?

var ThisInt = '9223372036854775808'
alert(ThisInt+'
' +parseFloat(ThisInt).toString()+'
' +parseInt(ThisInt).toString());

I need to perform an addition on it before casting it back as a string & would prefer not to have to slice it two if at all possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All Numbers in Javascript are 64 bit "double" precision IEE754 floating point.

The largest positive whole number that can therefore be accurately represented is 2^53 - 1. The remaining bits are reserved for the exponent.

Your number is exactly 1024 times larger than that, so loses 3 decimal digits of precision. It simply cannot be represented any more accurately.

In ES6 one can use Number.isSafeInteger( # ) to test a number to see if its within the safe range:

var ThisInt = '9223372036854775808'; 
console.log( Number.isSafeInteger( parseInt( ThisInt ) ) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...