Is there a way to set String.format so that it won't display 00 decimals? For example I would like:
String.format("%.2f", 12.345d)
to display 12.34
but
String.format("%.2f", 12.3d)
to display 12.3 instead of 12.30
Use DecimalFormat with setting rounding down, like:
DecimalFormat df = new DecimalFormat("0.##");
df.setRoundingMode(RoundingMode.DOWN) //rounding off
df.format(12.345d) //12.34
df.format(12.3d) //12.3
df.format(12.00) //12
Once you do the inital formatting with %.2f, one option is to run the resulting string through a regex based replace.
The regex : 0*$, should capture all trailing 0s at the end of the string/number.
So the full method call could be:
String.format("%.2f", 12.3).replaceAll("0*$", ""); //Will output "12.3"
String.format("%.2f %.2f", 12.3, 1.4).