Conditional Number Formatting In Java
Asked Answered
B

3

5

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!

Bogor answered 10/9, 2008 at 15:49 Comment(1)
DecimalFormat is available in jdk 1.4.Pederast
P
6

If you use DecimalFormat and specify # in the pattern it only displays the value if it is not zero.

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

Sample Code

 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]));
    }
Pederast answered 10/9, 2008 at 15:56 Comment(0)
S
2

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

Subtonic answered 10/9, 2008 at 15:57 Comment(0)
L
0
new Formatter().format( "%f", myFloat )
Lustrous answered 10/9, 2008 at 15:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.