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

5

40

300

+

+

@frontstuff_io

345

5

5 x 1

40

4 x 10

+

+

300

3 x 100

@frontstuff_io

345

5

5 x 1

5 x 10^0

40

4 x 10

4 x 10^1

+

+

300

3 x 100

3 x 10^2

@frontstuff_io

Computers use a binary system.

 

@frontstuff_io

Computers must convert decimal to binary.

 

@frontstuff_io

5

@frontstuff_io

5

1 x 2^2 (4)

5 - 4 = 1

1

@frontstuff_io

5

0 x 2^1 (2)

1 - 0 = 1

10

@frontstuff_io

5

1 x 2^0 (1)

1 - 1 = 0

101

@frontstuff_io

101

1

0

4

+

+

@frontstuff_io

Double-precision
floating-point format

@frontstuff_io

System.out.println(.1 + .2);

// 0.30000000000000004
print(.1 + .2)

# 0.30000000000000004

Python

Java

puts 0.1 + 0.2

# 0.30000000000000004

Ruby

Console.WriteLine("{0:R}", .1 + .2);

// 0.30000000000000004

C#

console.log(.1 + .2);

// 0.30000000000000004

JavaScript

Before ES2020
JavaScript only had

the number type

@frontstuff_io

5

@frontstuff_io

0.75

@frontstuff_io

0.75

0.75 x 2 = 1.5

1

@frontstuff_io

0.75

0.5 x 2 = 1

11

@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

@frontstuff_io

@frontstuff_io

Thank you!

@frontstuff_io

sarahdayan.dev

Why Javascript Numbers Are Weird (And How to Fix It)

By Sarah Dayan

Why Javascript Numbers Are Weird (And How to Fix It)

  • 312