px5x2
px5x2

Reputation: 1565

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?

Upvotes: 68

Views: 168900

Answers (3)

MajidJafari
MajidJafari

Reputation: 1110

You can use long npm package.

It let you have 64 bits integers in JavaScript.

You can also use BigInt JavaScript built-in method.

Upvotes: 5

sreejagaths
sreejagaths

Reputation: 469

May be late, but definitely helps others who run this situation first time.

I too wanted some calculation on large numbers in JavaScript. There are lot of libraries available to deal with such numbers. But most of them may waste lot of your time. Here, https://github.com/peterolson/BigInteger.js, is a direct, complete(for non node environment and node JS environments), and working solution for all operations on large numbers available. or find the following simple and sample working HTML code snippet which calculates modulo/remainder,

<script src="http://peterolson.github.com/BigInteger.js/BigInteger.min.js"></script>
<script type="text/javascript">
    function modTest(){
       var rem = bigInt("1738141852226360940").mod("32").valueOf();
       console.log(rem);
       document.getElementById("remainder").innerHTML = rem;
    }
</script>

<BODY onload="modTest();">
    <p id="remainder"></p>
</BODY>

Upvotes: 11

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382274

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.

Upvotes: 104

Related Questions