PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] Why is Number.MAX_SAFE_INTEGER 9,007,199,254,740,991 and not 9,007,199,254,740,992?

 July 21, 2022     ecmascript-6, ieee-754, integer, javascript     No comments   

Issue

ECMAScript 6's Number.MAX_SAFE_INTEGER supposedly represents the maximum numerical value JavaScript can store before issues arise with floating point precision. However it's a requirement that the number 1 added to this value must also be representable as a Number.

Number.MAX_SAFE_INTEGER

NOTE The value of Number.MAX_SAFE_INTEGER is the largest integer n such that n and n + 1 are both exactly representable as a Number value.

The value of Number.MAX_SAFE_INTEGER is 9007199254740991 (2^53−1).

– ECMAScript Language Specification

The JavaScript consoles of Chrome, Firefox, Opera and IE11 can all safely perform calculations with the number 9,007,199,254,740,992. Some tests:

// Valid
Math.pow(2, 53)                         // 9007199254740992
9007199254740991 + 1                    // 9007199254740992
9007199254740992 - 1                    // 9007199254740991
9007199254740992 / 2                    // 4503599627370496
4503599627370496 * 2                    // 9007199254740992
parseInt('20000000000000', 16)          // 9007199254740992
parseInt('80000000000', 32)             // 9007199254740992
9007199254740992 - 9007199254740992     // 0
9007199254740992 == 9007199254740991    // false
9007199254740992 == 9007199254740992    // true

// Erroneous
9007199254740992 + 1                    // 9007199254740992
9007199254740993 + ""                   // "9007199254740992"
9007199254740992 == 9007199254740993    // true

Why is it a requirement that n + 1 must also be representable as a Number? Why does failing this make the value unsafe?


Solution

I would say its because while Math.pow(2, 53) is the largest directly representable integer, its unsafe in that its also the first value who's representation is also an approximation of another value:

9007199254740992 == 9007199254740993 // true

In contrast to Math.pow(2, 53) - 1:

9007199254740991 == 9007199254740993 // false



Answered By - Alex K.
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing