Converting big number string to number

若如初见. 提交于 2019-12-10 22:23:45

问题


What way i can convert string with 16 digits and 2 fraction value to number ?

Currently when I try to convert Number('1234567890123456.12') will became to 1234567890123456. fraction values will be gone.

I just want to confirm without using any third party lib can i convert this string to number ?


回答1:


Unfortunately not. Javascript represents it's numbers using double precision floating point numbers. At 16 digits, it will only be able to store the integer component and not the part after the decimal point. You will need a bignum library to use this value.

EDIT: for reference the biggest integer you can use in JavaScript is 9,007,199,254,740,991

EDIT2: Thanks to Jeremy you can use a library like bignumberJS.




回答2:


Your number has too many algorisms, I've created an example that simulates in the first position of the array the maximum length possible in javascript.

var nums = [
    "12345678910111.12", 
    "1.5323",  
    "-42.7789"
];

nums.forEach(function(n) {
    console.log(parseFloat(n).toFixed(2));
});

https://jsfiddle.net/7zzz1qzt/



来源:https://stackoverflow.com/questions/45694479/converting-big-number-string-to-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!