views:

661

answers:

4

Hi, Is there a way to format a decimal as following:

100 -> "100" 100.1 -> "100.10"

i.e. if it is round omit the decimal part otherwise always show 2dp.

Thxs.

+1  A: 

Yes. You can use java.util.formatter. You can use a formatting string like "%10.2f"

dj_segfault
`String.format()` is a nice static wrapper for that. Not sure why you use '10', though.
Xr
Given no guidance on the size of the number, I chose 10 Ex Recto. We don't know if this is the price of a candy bar or a car.I believe you can also just do "%.2f" to leave the total size unbounded.
dj_segfault
DD wanted the decimal part omitted, if the amount is a round number of currency units.
jarnbjo
+1  A: 

you should do something like this:

public static void main(String[] args) {
    double d1 = 100d;
    double d2 = 100.1d;
    print(d1);
    print(d2);
}

private static void print(double d) {
    String s = null;
    if (Math.round(d) != d) {
        s = String.format("%.2f", d);
    } else {
        s = String.format("%.0f", d);
    }
    System.out.println(s);
}

which prints:

100

100,10

Stefan De Boey
Will Math.round(d) != d work? With floats it often != even if you think it is.
extraneon
the other way, if d would be 100.000000000000001 then it would still be printed as 100
Stefan De Boey
A: 

I doubt it. The problem is that 100 is never 100 if it's a float, it's normally 99.9999999999 or 100.0000001 or something like that.

If you do want to format it that way, you have to define an epsilon, that is, a maximum distance from an integer number, and use integer formatting if the difference is smaller, and a float otherwise.

Something like this would do the trick:

public String formatDecimal(float number) {
  float epsilon = 0.004; // 4 tenths of a cent
  if ( abs(Math.round(number) - number) < epsilon) {
     return String.format("%10.0f", number); // sdb
  } else {
     return String.format("%10.2f", number); // dj_segfault
  }
}
extraneon
A: 

I'd recommend using the java.text package:

double money = 100.1;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
System.out.println(formatter.format(money));

This has the added benefit of being locale specific.

duffymo
that doesnt work..always shows 2dp.
DD
That's how currencies work.
duffymo
You should never use a double to represent currencies. Either convert to longs and manage the decimal point yourself or use `BigDecimal` with a formatter.http://joda-money.sourceforge.net/ should be a nice library to use once it's done.
gpampara
I agree re: double != money, but that's not how the question was posed.
duffymo