Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript long integer

I have seen one of the weirdest things in javascript. The server side (spring):

   @RequestMapping(value = "/foo", method = RequestMethod.GET)    @ResponseBody    public Long foo() {       return 793548328091516928L;    } 

I return a single long value and:

$.get('/foo').done(function(data){     console.log(data); }); 

It represents the long integer as "793548328091516900" replacing (rounding indeed) the last two digits with 0s. When i make that GET request from any browser's address bar, the number represented correctly; thus this is a js issue, in my opinion.

Returning a string instead of long from server and handling it with:

var x = new Number(data).toFixed(); 

obviously a solution. But I am not so lucky that, I have to handle a complex POJO (converted to JSON) whose some fields (some are nested) are typed with java.lang.Long type. If i try to cast this POJO to another object does not having fields typed Long, it is obviously cumbersome.

Is there any solution to that obstacle in a clearer way?

like image 384
px5x2 Avatar asked Jun 26 '13 12:06

px5x2


People also ask

What is the largest integer in JavaScript?

Description. The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integers between -(253 – 1) and 253 – 1.

Is there long in JavaScript?

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

How do you declare a long variable in JavaScript?

var x = new Number(data). toFixed();

How do you handle large numbers in JavaScript?

Large numbers are the numbers that can hold huge memory and evaluation time is more than exceeds space and time to process. We can deal with large numbers in JavaScript using the data type BigInt. Advantages: It can hold numbers of large size.


1 Answers

In Java, you have 64 bits integers, and that's what you're using.

In JavaScript, all numbers are 64 bits floating point numbers. This means you can't represent in JavaScript all the Java longs. The size of the mantissa is about 53 bits, which means that your number, 793548328091516928, can't be exactly represented as a JavaScript number.

If you really need to deal with such numbers, you have to represent them in another way. This could be a string, or a specific representation like a digit array. Some "big numbers" libraries are available in JavaScript.

like image 143
Denys Séguret Avatar answered Oct 09 '22 10:10

Denys Séguret