Skip to content
← Back to Community
Floating Point Numbers
Profile icon
matthewproskils

Floating Point Numbers

Go into your python/javascript console and type out 0.1 + 0.2
result:

0.30000000000000004

Why is this?
Well, first we have to understand BINARY numbers.
Here is an example of a binary string

1010

We read binary from right to left, so we start with 0, which is 2^0x0, then, 2^1*1, etc.
Now, we do the negatives.. here's a new number:

1010.10011

We read negatives from left to right starting at the decimal point: 2^-1*1 (0.5), then 2^-2*0(0.25), then 2^-3*0(0.125), etc.
The problem with this is that we can't get exactly some decimal numbers.
So, the offsets add up, and then the floating 4 appears.

Voters
Profile icon
IsaacMiesner
Profile icon
seanlnge
Profile icon
PowerCoder
Profile icon
matthewproskils
Comments
hotnewtop
Profile icon
Coder100

Nice.

You can fix this by doing (1 + 2) / 10

Profile icon
matthewproskils

@Coder100 Yeah, but then you'll have to do ((0.1*10)+(0.2*10))/10

Profile icon
Coder100

oh yeah true @matthewproskils

Profile icon
Coder100

Something like:

function sum(a, b) { return (a * 10000 + b * 10000) / 10000 }

does the job
@matthewproskils

Profile icon
matthewproskils

@Coder100 Meh, It's much longer than 0.1+0.1