Jaanus Jaanus - 1 year ago 81
Javascript Question

Large numbers erroneously rounded in Javascript

See this code:


<script src="http://www.json.org/json2.js" type="text/javascript"></script>

<script type="text/javascript">

var jsonString = '{"id":714341252076979033,"type":"FUZZY"}';
var jsonParsed = JSON.parse(jsonString);
console.log(jsonString, jsonParsed);


When I see my console in Firefox 3.5, the value of jsonParsed is:

Object id=714341252076979100 type=FUZZY

I.e the number is rounded. Tried different values, the same outcome (number rounded).

I also don't get its rounding rules. 714341252076979136 is rounded to 714341252076979200, whereas 714341252076979135 is rounded to 714341252076979100.

EDIT: see first comment below. Apparently this is not about JSON, but something about Javascript number handling. But the question remains:


Answer Source

What you're seeing here is actually the effect of two roundings. Numbers in ECMAScript are internally represented double-precision floating-point. When id is set to 714341252076979033 (0x9e9d9958274c359 in hex), it actually is assigned the nearest representable double-precision value, which is 714341252076979072 (0x9e9d9958274c380). When you print out the value, it is being rounded to 15 significant decimal digits, which gives 14341252076979100.