Javascript 解析 int64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5353388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript parsing int64
提问by Oppdal
How can I convert a long integer (as a string) to a numerical format in Javascript without javascript rounding it?
如何在 Javascript 中将长整数(作为字符串)转换为数字格式而不使用 javascript 舍入?
var ThisInt = '9223372036854775808'
alert(ThisInt+'\r' +parseFloat(ThisInt).toString()+'\r' +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.
我需要在将它作为字符串返回之前对其进行加法运算,并且如果可能的话,我宁愿不必将其切成两半。
回答by Alnitak
AllNumbersin Javascript are 64 bit "double" precision IEE754floating point.
Javascript 中的所有数字都是 64 位“双”精度IEE754浮点数。
The largest positive whole number that can therefore be accurately represented is 2^53 - 1. The remaining bits are reserved for the exponent.
因此可以准确表示的最大正整数是 2^53 - 1。其余位保留给指数。
Your number is exactly 1024 times larger than that, so loses 3 decimal digits of precision. It simply cannot be represented any more accurately.
您的数字正好是该数字的 1024 倍,因此会丢失 3 位十进制数字的精度。它根本无法更准确地表示。
In ES6 one can use Number.isSafeInteger( # )
to test a number to see if its within the safe range:
在 ES6 中,可以使用Number.isSafeInteger( # )
一个数字来测试它是否在安全范围内:
var ThisInt = '9223372036854775808';
console.log( Number.isSafeInteger( parseInt( ThisInt ) ) );
There is also a BigIntegerlibrary available which should be able to help, though, and avoid you having to do all the string and bit twiddling yourself.
还有一个BigInteger库可用,它应该能够提供帮助,并且避免您必须自己做所有的字符串和一点点摆弄。
EDIT 2018/12there's now a native BigInt
class (and new literal syntax) landed in Chrome and NodeJS.
编辑 2018/12现在有一个原生BigInt
类(和新的文字语法)登陆 Chrome 和 NodeJS。
回答by Ates Goral
With a little help from recursion, you can directly increment your decimal string, be it representing a 64 bit number or more...
在递归的帮助下,您可以直接增加十进制字符串,无论是代表 64 位数字还是更多...
/**
* Increment a decimal by 1
*
* @param {String} n The decimal string
* @return The incremented value
*/
function increment(n) {
var lastChar = parseInt(n.charAt(n.length - 1)),
firstPart = n.substr(0, n.length - 1);
return lastChar < 9
? firstPart + (lastChar + 1)
: firstPart
? increment(firstPart) + "0"
: "10";
}
回答by fresskoma
回答by Christopher Armstrong
Have you tried using the Number class?var num = new Number(parseFloat(ThisInt))
您是否尝试过使用 Number 类?var num = new Number(parseFloat(ThisInt))
回答by Sachin Shanbhag
Just use Number(ThisInt)for this instead of Int or float
只需为此使用Number(ThisInt)而不是 Int 或 float