in Java, how to delete all 0s in float?

clerksx picture clerksx · Dec 1, 2011 · Viewed 15.8k times · Source

I'd like to change float like this way:

10.5000 -> 10.5 10.0000 -> 10

How can I delete all zeros after the decimal point, and change it either float (if there's non-zeros) or int (if there were only zeros)?

Thanks in advance.

Answer

maerics picture maerics · Dec 1, 2011

Well the trick is that floats and doubles themselves don't really have trailing zeros per se; it's just the way they are printed (or initialized as literals) that might show them. Consider these examples:

Float.toString(10.5000); // => "10.5"
Float.toString(10.0000); // => "10.0"

You can use a DecimalFormat to fix the example of "10.0":

new java.text.DecimalFormat("#").format(10.0); // => "10"