如何在JavaScript中显示整数? [英] How do I display whole number in JavaScript?

查看:131
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆