Skip to Content
Navigation:

A stick figure smiling

Here's a preview from my zine, How Integers and Floats Work! If you want to see more comics like this, sign up for my saturday comics newsletter or browse more comics!

Image of a comic. To read the full HTML alt text, click "read the transcript".

browse more comics! get the zine!
read the transcript!

how floats are printed

computers lie when they print out floats

(by rounding)

For example 0.12 isn’t 0.12, it’s actually (roughly):

0.119999999999999995559

is my computer LYING to me??? about NUMBERS?

the string -> float translation

If your program says:

x = 0.12

your interpreter / compiler needs to translate “0.12” into the float 0.119999999999999995559. Most languages will use the strtod (“string to double”) function from libc to do that translation.

the float -> string translation

This is where the rounding comes in. Computers round to make the numbers shorter and easier to read. 1.19999999999999995559

↪  1.2

float -> string translation is actually super complicated

Every floating point number needs a unique string representation.

There are a bunch of academic papers about how to do this well, search “Printing floating point numbers accurately” to read more about it.

some examples of printing floats

1.19900000000000006573

1.199

1.19999999000000001637

1.19999999

1.19999999999998996358

1.9999999999999

1.19999999999999995559

1.2

you can also print floats in base 16 or base 2

For example, 0.1 as a 32-bit float is:

base 16: 0x1.99999ap-4 (p-4 is the base 16. version of e-4)

base 2: 1.10011001100110011001101p-100

The base 2/base 16 representations are not rounded, but they’re rarely used.

Saturday Morning Comics!

Want another comic like this in your email every Saturday? Sign up here!

I'll send you one of my favourite comics from my archives every Saturday.
© Julia Evans 2024 | All rights reserved (see the FAQ for notes about licensing)