1

I use Java NumberFormat like this:

NumberFormat format = NumberFormat.getNumberInstance(locale);
format.maximumFractionDigits = 2;
String number = format.format(price);

When the double value is: 19.95 I get 19,95 localized correctly to German format. When the double value is: 19.5 I get 19,5 which is a wrong format.

If a price is 19.50 I need to get exactly two digists, i.e., 19,50. If a price is 19.00 I need to get zero digists, i.e., 19.

How can I do that?

Michael
  • 32,527
  • 49
  • 210
  • 370

1 Answers1

2

This worked for me:

    NumberFormat format = NumberFormat.getNumberInstance(Locale.GERMAN);
    format.setMinimumFractionDigits(2);
    format.setMaximumFractionDigits(2);
    double price = <your price>;
    int priceAsInt = (int)price;
    if(((double)priceAsInt) == price) {
        String number = String.valueOf(priceAsInt);
        System.out.println(number);
    } else {
        String number = format.format(price);
        System.out.println(number);
    }
dimplex
  • 494
  • 5
  • 9