Processing float values: decimal output and IEEE 754 bit patterns

Hello folks!

Inspired by this recent discussion:

Why are there individual keywords for different multiples of π

I thought float display and storage deserved a separate topic.

Exploration of float display and storage:

println()              normal readable decimal display
String.format()        formatted decimal display
nf()                   Processing formatted decimal display
System.out.printf()    Java formatted decimal display
floatToIntBits()       actual 32-bit float bit pattern
// Normal Processing println() display:
println("PI         = " + PI);

// Decimal text representations for display purposes only.
// The float value is stored internally as a 32-bit IEEE 754 binary value.
println(String.format("PI         = %.16f", PI));
println("PI         = " + nf(PI, 1, 16));
System.out.printf("PI         = %.16f%n", PI);

// Prints the 32-bit IEEE 754 float bit pattern as hex and binary:
println("PI hex     = " + hex(Float.floatToIntBits(PI), 8));
println("PI binary  = " + binary(Float.floatToIntBits(PI), 32));

References:

Goldberg: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Processing float reference:

Processing nf() reference:

Java Float.toString() and Float.floatToIntBits() reference:

Float.floatToRawIntBits() is left as an exercise for the reader.

:)

1 Like