0

I have the folowing code:

<a href="javascript:Add(23905762501722146)">Click</a>

function Add(id) {

    alert(id);

}

The value in the alert is 23905762501722144 (-2) from the original value.

Why does this happen?

https://jsfiddle.net/wvtqostd/4/

helloworld
  • 527
  • 6
  • 21
  • 2
    Tip: Use as string `Add("23905762501722146")` if you can(not to use for numerical operations). – DontVoteMeDown Mar 02 '15 at 17:49
  • 3
    Because `23905762501722146` is larger than what JS can represent precisely as integer. – Felix Kling Mar 02 '15 at 17:50
  • 1
    In Javascript, all numbers are floating numbers and are prone to floating point approximation. // This holds true 10000000000000000 === 10000000000000001 Avoid numbers when approximation is not permitted. If you need to manipulate big integers in Javascript use a library for that. http://silentmatt.com/biginteger/ https://github.com/substack/node-bigint – vmx Mar 02 '15 at 18:05

2 Answers2

4

log2(23905762501722146) ~= 54.408

JavaScript stores all numbers - including integers - as double precision floats. Double precision mantissa/significand contains 52 bits of information, so some information gets lost storing so long/precise number as you have.

Roland Pihlakas
  • 4,246
  • 2
  • 43
  • 64
4

Because 23905762501722144 is to big to represent as integer value... try sending it as string value.

lem2802
  • 1,152
  • 7
  • 18