Domanda

is there a class in Java that lets you format a number like "102203345.32" to this "102.203.345,32" and return a string type?

I would like to obtain a String where the thousands are separated by the '.' and the decimals are separated by a comma ','.

Could someone help me please? I found a class DecimalFormat and I tried to customize it:

public class CustomDecimalFormat {
static public String customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      return output;
}
}

but when I call the customFormat method like this: CustomDecimalFormat.customFormat("###.###,00") I get an exception...

What should I do?

Thanks!

È stato utile?

Soluzione

Be sure to read and understand the Special Pattern Characters section of the Javadoc, especially this note:

The characters listed here are used in non-localized patterns. Localized patterns use the corresponding characters taken from this formatter's DecimalFormatSymbols object instead, and these characters lose their special status.

If you have done that, it should be clear to you that you must use the appropriate constructor and supply the appropriately configured separator/grouping chars, whereas in the pattern itself the dot and the comma have a special meaning.

All the complexity above is there for your convenience, actually: it allows you to customize the number format and have it localized.

Here's a code sample which worked for me:

final DecimalFormatSymbols syms = new DecimalFormatSymbols();
syms.setDecimalSeparator(',');
syms.setGroupingSeparator('.');
DecimalFormat myFormatter = new DecimalFormat("###,###.00", syms);
System.out.println(myFormatter.format(1234.12));

You can also use a variant where you apply the localized pattern, for more intuitive code:

final DecimalFormatSymbols syms = new DecimalFormatSymbols();
syms.setDecimalSeparator(',');
syms.setGroupingSeparator('.');
DecimalFormat myFormatter = new DecimalFormat("", syms);
myFormatter.applyLocalizedPattern("###.###,00");
System.out.println(myFormatter.format(1234.12));

Altri suggerimenti

First of all, you misplaced the comma and decimal points. Your format should be : ###,###.00 instead of ###.###,00 ...

Also check with your Locale, it has an effect on the format. See the link below.

http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

You can try GERMAN number format

NumberFormat.getNumberInstance(Locale.GERMAN).format(102203345.32)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top