0

Consider the following JavaScript code:

alert(9999999999999999);

When I am executing this file, I get the following output:

alert message

Why I am getting 100000000000 in alert()? Can anyone give suggestions please?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Mahendra Jella
  • 5,450
  • 1
  • 33
  • 38
  • 1
    The maximum number in JS is 9007199254740992 – Willem D'Haeseleer Nov 29 '13 at 17:52
  • if u want to print it then put inside qoute – Pranav C Balan Nov 29 '13 at 17:54
  • @willem Dhaeseleer if the number exceeds the max number ....is there any alternatives to display that number. – Mahendra Jella Nov 29 '13 at 17:54
  • 2
    Watch this talk, it will tell you all you ever need to know about IEEE 754 number implementations. A MUST WATCH for programmers, really: Bartek Szopka: Everything you never wanted to know about JavaScript numbers -- JSConf EU 2013; http://www.youtube.com/watch?v=MqHDDtVYJRI – Mörre Nov 29 '13 at 17:55
  • Try: alert("9999999999999999"); That will probably work. No clue why this doesn't work, cause it should! As you will notice when working with javascript, some things are really curious. When i have to say a reason out of my head, i think its a compile error in javascript itself. Probably something to do with number being to big for integer and a misinterpretation with casting. – Patrick Aleman Nov 29 '13 at 18:02
  • but it treats as a string @PatrickAleman – Mahendra Jella Nov 29 '13 at 18:04
  • Thats even more curious. Did you test it? – Patrick Aleman Nov 29 '13 at 18:09
  • There are a number of libraries for JavaScript like https://github.com/MikeMcl/bignumber.js/ (Google 'javascript big integer decimal number' to find many others). – David Conneely Nov 29 '13 at 18:46

2 Answers2

1

This is an issue with the way JavaScript deals with numbers. The largest possible integer value in JavaScript is 9007199254740992.

To compare:

Your number: 9007199254740992
Largest num: 9999999999999999

So if you test 9007199254740992 it will work fine, but one number more (9007199254740993) and JavaScript will return 9007199254740992 still.

To give further detail, JavaScript numbers are 64-bit floating point values, the largest exact integral value is 253.

Pippin
  • 1,066
  • 7
  • 15
0

It's represented as double, and that number cannot be stored exactly as a double because it has too many significant digits. The result you got back is the closest double that can be represented.

See http://babbage.cs.qc.cuny.edu/IEEE-754.old/64bit.html

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190