DEV Community

Geoff Bourne
Geoff Bourne

Posted on

Trim trailing zeroes when formatting float in Java

Simple problem, but surprisingly non-obvious answer:

The output of

System.out.printf("%f%n", 1.0);
Enter fullscreen mode Exit fullscreen mode

is

1.000000
Enter fullscreen mode Exit fullscreen mode

however, I really don't want those extra, trailing zeroes and I don't want to lose precision in other cases.

Looking again through the Formatter docs, I was surprised to find that only a fixed number of decimal places could be specified, such as %.1f. That won't work for this problem since 1.0005 gets formatted as 1.0.

Since this is a "decimal point" problem, it turns out to not be a surprise that BigDecimal is the solution.

From this

System.out.println(BigDecimal.valueOf(1.0));
System.out.println(BigDecimal.valueOf(1.00000000));
System.out.println(BigDecimal.valueOf(1.000000001));
Enter fullscreen mode Exit fullscreen mode

I get what I wanted:

1.0
1.0
1.000000001
Enter fullscreen mode Exit fullscreen mode

Note that the toString is actually implemented like toEngineeringString, but the formatting can be constrained to plain decimal formatting with toPlainString.

For example, the following

System.out.println(BigDecimal.valueOf(0.000000005300));
System.out.println(BigDecimal.valueOf(0.000000005300).toEngineeringString());
System.out.println(BigDecimal.valueOf(0.000000005300).toPlainString());
Enter fullscreen mode Exit fullscreen mode

outputs

5.3E-9
5.3E-9
0.0000000053
Enter fullscreen mode Exit fullscreen mode

Finally, to make sure the desire to remove trailing zeroes didn't introduce a huge performance problem, I benchmarked 10 million iterations of each formatting 5,000 random values. BigDecimal formatting seems to be only very slightly slower:

formatted took PT5.3975531S
BigDecimal took PT5.6573979S
Enter fullscreen mode Exit fullscreen mode

Top comments (0)