How to format numbers as strings to be in the form “xxx.xxx.xxx,yy”in Java?

家住魔仙堡 提交于 2019-12-08 12:08:55

问题


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!


回答1:


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));



回答2:


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




回答3:


You can try GERMAN number format

NumberFormat.getNumberInstance(Locale.GERMAN).format(102203345.32)


来源:https://stackoverflow.com/questions/22456350/how-to-format-numbers-as-strings-to-be-in-the-form-xxx-xxx-xxx-yyin-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!