2014-03-19 33 views
0

我只是試圖添加1到一個大數字,如果滿足一些條件。下面是我的javascript:如何將1添加到JavaScript中的大數字?

console.log('n1->'+n1+ ' - ' + typeof(n1)); 
console.log('n2->'+n2); 

if(n1 != null && n2 != n1){ 
    console.log('adding 1'); 
    n2 = n1 + 1; 
} 
console.log('n2->'+n2); 

,這裏是控制檯輸出:

n1->443751754287812600 - number 
n2->null 
adding 1 
n2->443751754287812600 

我期待有n2=443751754287812601甚至n2=4437517542878126001。你能解釋它爲什麼不起作用嗎?以及如何正確地完成總和?

感謝您的幫助。

+0

閱讀:http://stackoverflow.com/questions/307179/what-is-javascripts -max-int-what-the-highest-integer-value-a-number-can-go-t – noobcode

回答

5

JavaScript中的數字在大多數語言中通常被稱爲雙數:IEEE754 double precision floating point numbers

它們的精度有限(最大整數爲2^53 = 9,007,199,254,740,992),您只需通過該限制即可。

+1

補充一下這個很好的答案,你可以使用一個圖書館爲bignumber,在這裏回答的話題http://stackoverflow.com/questions/3072307 /有--A-BIGNUM庫換的JavaScript – QuarK

1

這個數字太大,所以你可以做的是你可以使用strint或其他庫,這個庫允許你使用任意大的整數,通過將它們存儲在字符串中。或者您可以使用BigInteger.js

檢查該鏈接strint

https://github.com/rauschma/strint

谷歌更多