javascript large integer round because precision? (why?)
Asked Answered
M

2

4

If you do

for(var i = 0; i < 30; i++){console.log(i + " == " + 78764357878563800 + " ? ");console.log((78764357878563790+i) == 78764357878563800);}

You start comparing values from 78764357878563790 to 78764357878563790+29, so... like you see if you run it, you get true from i = 8 to 24.

So I don't know if I don't get it, but isn't supposed to exist the maxint (which I dont know) and a maxint-1??? and then max be different than maxint-1?

I suppose this is precision like floating numbers... but that isn't supposed to only hit floating numbers and for example, number+1 always gives the successor? (so in the example above, if i = 78764357878563790 and add i++, then you enter an infinite loop.

I know before hand that this type of spacing between numbers exist for floating points, but never hit a case where also the integers cant represent i+1 and i-1 (I always thinked that unsigned maxint + 1 would carry and give 0).

Any suguestions in:

  • which is the max number and what is the anterior number in js.
  • how to handle or know when this behaviour for integers will start happening.
  • how to handle this large numbers and more big than this would be nice.
Molder answered 27/4, 2011 at 23:56 Comment(0)
E
8

There are no integers in Javascript.

Numbers are double precision floating point, which gives you a precision of 15-16 digits. This is consistent with your results.

Eldwon answered 28/4, 2011 at 0:1 Comment(0)
M
1

As I suspected... so there is no integers in JS.

So that is you don't have integers in js like you would spec in other langs (they are thus most like an alias), altought they are confusing if you come from other language that has int and unsigned int and know the behaviour in the back.

So for handle big ints, I suguest to myself something like

if(someInt+1 == someInt || someInt-1 == someInt) { //use big number }

Or something like that, so far I only searched for BigInt libs in js, found one result here for integers

And for floating point

So I have my 3 questions ansered.

  • which is the max number and what is the anterior number in js. The same than a Float can give... but you will start getting gaps in some place... that is adding +1 to it will give the same number instead of consecutive.... so you have 2 "max ints" the max int that you can have adding +1 and get the next number and the max integer that is hable to give a 64-bit floating point number.

  • how to handle or know when this behaviour for integers will start happening.

  • how to handle this large numbers and more big than this would be nice.

Use one of the 2 above: a big int library or the check "someInt+1 == someInt || someInt-1 == someInt".

Molder answered 28/4, 2011 at 21:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.