A presentation at Frontend Love Meetup by Sarah Dayan
Why Javascript Numbers Are Weird (And How to Fix It) @frontstuff_io
@frontstuff_io
We use a decimal system. @frontstuff_io
0 12 345 6789 @frontstuff_io
345 @frontstuff_io
345 300 + 40 + 5 @frontstuff_io
345 300 3 x 100 + 40 4 x 10 + 5 5x1 @frontstuff_io
345 300 + 40 + 5 3 x 100 4 x 10 5x1 3 x 10^2 4 x 10^1 5 x 10^0 @frontstuff_io
Computers use a binary system. @frontstuff_io
Computers must convert decimal to binary. @frontstuff_io
5 @frontstuff_io
1 5 1 x 2^2 (4) 5-4=1 @frontstuff_io
5 10 0 x 2^1 (2) 1-0=1 @frontstuff_io
5 101 1 x 2^0 (1) 1-1=0 @frontstuff_io
1 0 1 4 + 0 + 1 @frontstuff_io
Double-precision floating-point format @frontstuff_io
Java 1 System.out.println(.1 + .2); 2 3 // 0.30000000000000004 Python 1 print(.1 + .2) 2 3 # 0.30000000000000004 Ruby 1 puts 0.1 + 0.2 2 3 # 0.30000000000000004 C# JavaScript 1 Console.WriteLine(“{0:R}”, .1 + .2); 2 3 // 0.30000000000000004 1 console.log(.1 + .2); 2 3 // 0.30000000000000004
Before ES2020 JavaScript only had the number type @frontstuff_io
0.75 @frontstuff_io
0.75 1 0.75 x 2 = 1.5 @frontstuff_io
0.75 11 0.5 x 2 = 1 @frontstuff_io
0.75 O.11 @frontstuff_io
5.75 @frontstuff_io
console.log(.1 + .2); // 0.30000000000000004 @frontstuff_io
0.1 @frontstuff_io
0.1 + 0.2 @frontstuff_io
Same goes with Large integers @frontstuff_io
Number.MAX_SAFE_INTEGER; // 9007199254740991 Number.MAX_SAFE_INTEGER + 2; // 9007199254740992 @frontstuff_io
9007199254740991 -9007199254740991 @frontstuff_io
What to do instead? @frontstuff_io
(1 + 2) / 10^1 @frontstuff_io
Dinero({ amount: 500, currency: “USD” }); // represents $5 @frontstuff_io
10n @frontstuff_io
9007199254740991n + 2n; // 9007199254740993n @frontstuff_io
Arbitrary precision math is slower than floating point math. @frontstuff_io
Arbitrary precision integers are still new. @frontstuff_io
bartaz.github.io/ieee754-visualization 0.30000000000000004.com floating-point-gui.de @frontstuff_io
youtu.be/MqHDDtVYJRI @frontstuff_io
Thank you! sarahdayan.dev @frontstuff_io
View Why JavaScript Numbers Are Weird (and How to Fix It) on Notist.
Dismiss
The following resources were mentioned during the presentation or are useful additional information.