Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting big number string to number

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 ?

like image 937
Nitish Avatar asked Sep 16 '25 23:09

Nitish


2 Answers

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.

like image 70
PilotInPyjamas Avatar answered Sep 19 '25 04:09

PilotInPyjamas


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/

like image 42
Yuri Ramos Avatar answered Sep 19 '25 03:09

Yuri Ramos