I'd like to format a number to maximum N decimal places. There's another similar and popular question here, but that's not exactly what I'm looking for.
I'm looking for something like this, let's say I want max. 2 places, so this would be:
1.00 -> "1" (not "1.00")
1.20 -> "1.2" (not "1.20")
1.23 -> "1.23"
1.234 -> "1.23"
1.235 -> "1.24"
The difference to the other question is that I don't want trailing zeros behind the comma if I don't need them.
I'd like to know whether this is doable with String.format()
, not with Math.round()
, or DecimalFormat. The other question shown above provides a solution with DecimalFormat.
The answer does not need to be variable given N as an argument. I just chose N as an example.