Conditional Number Formatting In Java


Answers

Check out the DecimalFormat class, e.g. new DecimalFormat("0.##").format(99.0) will return "99".

Question

How can I format Floats in Java so that the float component is displayed only if it's not zero? For example:

123.45 -> 123.45
99.0   -> 99
23.2   -> 23.2
45.0   -> 45

Edit: I forgot to mention - I'm still on Java 1.4 - sorry!




How to remove .0 after a double while converting to string

Use the class DecimalFormat

double d = 2.0;
DecimalFormat formatter = new DecimalFormat("0.##");
String formated = formatter.format(d).toString();



Links



Tags