javascript large integer round because precision? (why?)

后端 未结 2 612
逝去的感伤
逝去的感伤 2020-11-28 16:41

if you type 78764357878563812 in chrome or in safari, then you get

If you do

for(var i = 0; i < 30; i++){console.log(i + \" == \" + 7876435787856         


        
相关标签:
2条回答
  • 2020-11-28 17:05

    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.

    0 讨论(0)
  • 2020-11-28 17:28

    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

    • Huge Integer JavaScript Library

    And for floating point

    • Arbitrary precision Float numbers on JavaScript
    • Java floating point high precision library

    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".

    0 讨论(0)
提交回复
热议问题