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

lucian.marcuta
  • 1,250
  • 1
  • 16
  • 29

2 Answers2

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
chengpohi
  • 14,064
  • 1
  • 24
  • 42
  • I prefer RoundingMode.UNNECESSARY myself. Otherwise your comment of "rounding off" is misleading. Also RoundingMode.HALF_UP works equally well. – Uncle Iroh Jun 30 '16 at 16:11
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"
m_callens
  • 6,100
  • 8
  • 32
  • 54
  • 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)`. – Pshemo Jun 30 '16 at 15:53
  • 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. – Uncle Iroh Jun 30 '16 at 15:54
  • @Pshemo that's true, I didn't think of that – m_callens Jun 30 '16 at 15:54