如何在JavaScript中显示整数? [英] How do I display whole number in JavaScript?
问题描述
var product = 50000000 * 39048902222211111111111111111111:
alert(product) ; //这给了我1.9524451111105555e + 39。
是否有任何方法显示整个数字,而不是 e + 39 东西?
您试图表示的整数值大于Javascript可以处理的整数精度(fixed-精确算术)。最大安全整数为 -9007199254740991
至 9007199254740991
或 +/-(2 ^ 53-1 )
虽然 9007199254740992
可以表示为不安全。为什么?试试 jsFiddle
Javascript
alert(9007199254740992 + 1);
输出
9007199254740992
请参阅 specification ecma-262 / 5.1 /#sec-8.5
您可以使用库来进行任意精度算术,或自行推出。
使用一个这样的库, bignumber。 js
,使用 require.js
Javascript
require.config({
paths:{
bignumberjs:'https://raw.github.com/MikeMcl/bignumber.js/master/bignumber.min'
}
});
必须(['bignumberjs'],函数(BigNumber){
BigNumber.config({
EXPONENTIAL_AT:100
});
var product = new BigNumber('50000000')。times('39048902222211111111111111111111');
alert(product);
});
输出
1952445111110555555555555555555550000000
关于jsFiddle
Let's say I write this in JS:
var product = 50000000*39048902222211111111111111111111:
alert(product); //this gives me 1.9524451111105555e+39.
Is there any way to display the whole number, and not that e+39 thing?
The integer values you are trying to represent are larger than the integer precision that Javascript can handle (fixed-precision arithmetic). Maximum safe integers are -9007199254740991
to 9007199254740991
or +/-(2^53-1)
While 9007199254740992
can be represented it is considered unsafe. Why? Try this jsFiddle
Javascript
alert(9007199254740992 + 1);
Output
9007199254740992
See specification ecma-262/5.1/#sec-8.5
But you can use a library for arbitrary-precision arithmetic, or roll your own.
Using one such library, bignumber.js
, loaded using require.js
Javascript
require.config({
paths: {
bignumberjs: 'https://raw.github.com/MikeMcl/bignumber.js/master/bignumber.min'
}
});
require(['bignumberjs'], function (BigNumber) {
BigNumber.config({
EXPONENTIAL_AT: 100
});
var product = new BigNumber('50000000').times('39048902222211111111111111111111');
alert(product);
});
Output
1952445111110555555555555555555550000000
On jsFiddle
这篇关于如何在JavaScript中显示整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!