2

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

0

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

I prefer RoundingMode.UNNECESSARY myself. Otherwise your comment of "rounding off" is misleading. Also RoundingMode.HALF_UP works equally well.
0

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"

3 Comments

While this solves case described in question, it could be worth providing solution for general case like String.format("%.2f %.2f", 12.3, 1.4).
He would probably also want to get the period (.) in the case where it's double .00. So perhaps .replaceAll("\\.{0,1}0*$", "") or something.
@Pshemo that's true, I didn't think of that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.