Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent JavaScript Number function from rounding big numbers

Tags:

javascript

I have a string value ' 9223372036854775807 '. I use Number() function in JavaScript to convert it to a number value using the following Code

var numericVal = Number(' 9223372036854775807 ');

when i check the value in numericVal, it is 9223372036854776000. How can I get the equivalent value for the string representing the Number?

like image 243
Santron Manibharathi Avatar asked Mar 20 '13 16:03

Santron Manibharathi


2 Answers

JavaScript numbers are Double Precision Floats; the largest integer that can be precisely stored is 2^53 (9007199254740992). If you actually need it in a number you have some fun math ahead of you, or you can use a library such as big.js

like image 165
Dave Lasley Avatar answered Sep 23 '22 00:09

Dave Lasley


You can compare strings that represent big integers as strings-

a longer string of integers is larger, otherwise compare characters in order.

You can sort an array of integer-strings

function compareBigInts(a, b){
    if(a.length== b.length) return a>b? 1:-1;
    return a.length-b.length;
}

or return the larger of two strings of digits

function getBiggestBigInts(a, b){
    if(a.length== b.length) return a>b? a:b;
    return a.length>b.length? a: b;
}

//examples

var n1= '9223372036854775807', n2= '9223372056854775807',
n3= '9223',n2= '9223372056854775817',n4= '9223372056854775';

getBiggestBigInts(n1,n2);>> 9223372056854775807

[n1,n2,n3,n4].sort(compareBigInts);>>

9223
9223372056854775
9223372036854775807
9223372056854775817

Just make sure you are comparing strings.

(If you use '-' minus values,a 'bigger' string value is less)

By the way,you sort big decimals by splitting on the decimal point and comparing the integer parts. If the integers are the same length and are equal, look at the the decimal parts.

like image 36
kennebec Avatar answered Sep 21 '22 00:09

kennebec