How to count the number of digits of a floating number?

Hello @Richard,

In the example you provided the Processing version of PI is a float:
float PI = (float) Math.PI;

This may not be obvious to everyone.

The example you provided will not correctly display PI to 10 decimal digits.

This:
println(String.format("%12.20f", PI)); //Your example to try... I changed decimal places to 20

Is the equivalent of this:
println(String.format("%12.20f", (double) ((float) Math.PI)));

And will not restore the significant digits that are lost casting from a float to a double.

This will display PI with the correct significant digits available:
println(String.format("%12.20f", Math.PI)); // double precision floating point

I stumbled across this years ago and and sorted it out at that time… it is important to provide clarity on this.

References:
https://github.com/processing/processing4/blob/master/core/src/processing/core/PConstants.java
https://en.wikipedia.org/wiki/Pi
https://en.wikipedia.org/wiki/Double-precision_floating-point_format

Example:

println(String.format("%12.20f", PI));
println();

println(String.format("%12.20f", (double) ((float) Math.PI)));
println();

println(String.format("%12.20f", Math.PI));
println();

:)

1 Like