Skip to content Skip to sidebar Skip to footer

Why Does `btoa` Encoding In Javascript Works For 20 Digit String And Not 20 Digit Int?

Consider the following btoa output btoa(99999999999999999999) 'MTAwMDAwMDAwMDAwMDAwMDAwMDAw' btoa(99999999999999999998) 'MTAwMDAwMDAwMDAwMDAwMDAwMDAw' btoa('99999999999999999998'

Solution 1:

Because of floating point imprecision. Remember, JavaScript doesn't have integers except temporarily during certain calculations; all JavaScript numbers are IEEE-754 double-precision floating point. 99999999999999999999 is not a safe integer value in IEEE-754 numbers, and in fact if you do this:

console.log(99999999999999999999);

...you'll see

100000000000000000000

The max safe integer (e.g., integer that won't be affected by floating point imprecision) is 9007199254740991.

Since btoa accepts a string (when you pass it a number, the number just gets converted to string), just put quotes around your value:

btoa("99999999999999999999")
=> OTk5OTk5OTk5OTk5OTk5OTk5OTk=

Of course, if the value is the result of a math calculation, you can't do that. You'll have to change whatever it is that's calculating such large numbers, as they exceed the precise range of the number type.

Post a Comment for "Why Does `btoa` Encoding In Javascript Works For 20 Digit String And Not 20 Digit Int?"