Simple problem, but surprisingly non-obvious answer:
The output of
System.out.printf("%f%n", 1.0);
is
1.000000
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));
I get what I wanted:
1.0
1.0
1.000000001
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());
outputs
5.3E-9
5.3E-9
0.0000000053
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
Top comments (0)