Reputation: 4830
The code evaluates true
when the number string is within +/- 2^53 and false when it is outside of that range.
num_string = "9007199254740992"
new_num = (new Number(num_string)+"")
num_string === new_num
This seems to work, but what is the correct way to detect a number overflow? This would fail, for example, if the initial string had leading zeros 007
. This is not an overflow, that should not fail.
EDIT: I have to use a string, I'm converting to from a string to a number and want to know if my number got messed up. So, I am testing a string (not a number).
Upvotes: 2
Views: 57
Reputation: 23250
You don't need to use a string:
9007199254740993 === 9007199254740992 // true
However, you should be checking against Number.MAX_SAFE_INTEGER
, which will tell you the highest integer you can use without loss of precision.
Number.MAX_SAFE_INTEGER // 9007199254740991
So check against that:
if (num > Number.MAX_SAFE_INTEGER) {
// not safe!
}
You can also use a function (credit to @RickHitchcock
):
Number.isSafeInteger(num)
Upvotes: 2