0

Can anybody solve the following problem with javascript

var i = 10152233307863175;
alert(i.toString());

alert shows value 10152233307863176. Any solution. Problem is when I get json object on client and when string is converted to json it contains wrong values.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Asad Ullah
  • 87
  • 4
  • It's showing that value because is a String, it is converting it correctly, whats the problem? The alert won't show you the quotes – Pablo Matias Gomez Jul 18 '14 at 15:26
  • @PabloMatíasGomez: Look closely at the last figures. – sampathsris Jul 18 '14 at 15:27
  • @PabloMatíasGomez - Alerted value ends in `6` whereas the original value ends in `5` – techfoobar Jul 18 '14 at 15:27
  • 6
    Strongly related: [What is JavaScript's Max Int? What's the highest Integer value a Number can go to without losing precision?](http://stackoverflow.com/q/307179/1169798). – Sirko Jul 18 '14 at 15:27
  • As in most languages, when you exceed the maximum integer size you get a float. It isn't a to string conversion issue: your actual number is lost as soon as you type it. – Álvaro González Jul 18 '14 at 15:28
  • That has to deal with floating point precision (all numbers are double in javascript). It is the neartes value representable. There was asked before in stack overflow but i can't find it. – Prusse Jul 18 '14 at 15:28

2 Answers2

2

This is a limitation in the precision of the numeric data format that javascript uses (double precision floating point).

The best way of storing that value, assuming you don't need to do any mathematical operations, is storing it as a string in the first place.

Simon
  • 2,721
  • 1
  • 13
  • 15
0

MDN has this to say about numbers in JavaScript.

Numbers in JavaScript are "double-precision 64-bit format IEEE 754 values", according to the spec.

There is no real integers in JavaScript. According to this source:

ECMAScript numbers are represented in binary as IEEE-754 (IEC 559) Doubles, with a resolution of 53 bits, giving an accuracy of 15-16 decimal digits; integers up to just over 9e15 are precise, ...

Your number 10152233307863175 contains 17 digits. Since the number is represented as a floating point number, JavaScript tries to do it's best and set bits in a way that the resulting number is closest to the supplied number.

sampathsris
  • 21,564
  • 12
  • 71
  • 98