0

I have this number in javascript - 1234567890123456789

This number is apparently a magical number, because when interpreted the lowest two digits magically turn into zeros!!!!!!! Run it through the console and you get this: 1234567890123456800

But wait - theres more. try out this number: 12345678901234568999

Console outputs 12345678901234570000

What is going on here? Have I finally lost my mind or is this some sort of cosmic joke?

BlinkyTop
  • 1,124
  • 3
  • 14
  • 19
  • what datatype are you using there? – Arijit Mukherjee Jun 18 '14 at 04:22
  • 1
    Have you really never heard of number limits for certain data types? – Hanky Panky Jun 18 '14 at 04:22
  • You are overflowing the capacity of JavaScript's number type. – helderdarocha Jun 18 '14 at 04:23
  • http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t – Hanky Panky Jun 18 '14 at 04:24
  • Lol. So how do you suppose I represent this number? Lol! It's a number. As I recall, that's the datatype that JS uses for ALL numbers. Furthermore if it were a number limit it would be rolling over, not this seemingly randomized rounding crap. – BlinkyTop Jun 18 '14 at 04:25
  • Depending on the meaning of the number, sometimes strings are used instead of actual numbers. E.g. if you have large IDs, there is no need to store them as numbers since you are not going to do (mathematical) computations with them anyways. – Felix Kling Jun 18 '14 at 04:27
  • I am doing 64 bit bitwise operations on numbers that have to be masked as integers and there's no way to turn off floating point mode? – BlinkyTop Jun 18 '14 at 04:30
  • @BlinkyTop: JS' bitwise operators convert the values to *32 bit* numbers anyway. – Felix Kling Jun 18 '14 at 04:30

1 Answers1

1

Numbers in JavaScript are floating point numbers. As such, integers/numbers above a certain value are prone to precision errors, as you have experienced first hand.

Any number larger than Number.MAX_SAFE_INTEGER, or 9007199254740991, is going to experience precision issues. That is, only integers up to 15 digits are guaranteed to be exact.

Allen G
  • 1,160
  • 6
  • 8
  • 1
    How am I supposed to represent a 64 bit integer value in javascript? – BlinkyTop Jun 18 '14 at 04:26
  • 1
    @BlinkyTop: [JavaScript can't handle 64-bit integers, can it?](http://stackoverflow.com/q/9643626/218196) – Felix Kling Jun 18 '14 at 04:29
  • @BlinkyTop—use a library like [*BigInt.js*](http://www.leemon.com/crypto/BigInt.html), or write your own. They use strings, not numbers. – RobG Jun 18 '14 at 04:30
  • As mentioned, 64-bit integers aren't supported natively by JavaScript, so you will need some type of BigInt library, such as the one RobG posted. The link Felix provided also mentions a math.Long library: http://docs.closure-library.googlecode.com/git/class_goog_math_Long.html – Allen G Jun 18 '14 at 04:33