Conditional Number Formatting in Java

How can I format Floats in Java so that the displayed component is only displayed if it is not equal to 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 in Java 1.4 - sorry!

+5
source share
3 answers

If you use DecimalFormat and specify # in the template, it only displays the value if it is not equal to zero.

See my question. How do I format a number in java?

Code example

 DecimalFormat format = new DecimalFormat("###.##");

    double[] doubles = {123.45, 99.0, 23.2, 45.0};
    for(int i=0;i<doubles.length;i++){
        System.out.println(format.format(doubles[i]));
    }
+6
source

DecimalFormat, . DecimalFormat ( "0. ##" ). (99.0) "99".

+2
new Formatter().format( "%f", myFloat )
0
source

All Articles