开发者

Decimal separator in NumberFormat

Given a locale java.text.NumberFormat:

NumberFormat numberFormat = NumberFormat.getInstance();

How can I get the character used as Decimal separator (if it's a comma or a point) in that numberformat? How can I modify this property without having to use new DecimalFormat(f开发者_C百科ormat)?

Thanks


The helper class DecimalFomatSymbols is what you are looking for:

DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance();
DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
char sep=symbols.getDecimalSeparator();

To set you symbols as needed:

//create a new instance
DecimalFormatSymbols custom=new DecimalFormatSymbols();
custom.setDecimalSeparator(',');
format.setDecimalFormatSymbols(custom);

EDIT: this answer is only valid for DecimalFormat, and not for NumberFormat as required in the question. Anyway, as it may help the author, I'll let it here.


I agree with biziclop and Joachim Sauer that messing with decimal and grouping separators and doing this work manually, can cause a lot of problems. Use of the locale parameter in the NumberFormat getInstance method does all the work for you automatically. And you can easily disable the thousand grouping separator, if you wish so.

The following junit test method (which passes) shows this behavior based on English and German locale.

public void testFormatter() {
    DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(Locale.UK);
    assertEquals('.', formatter.getDecimalFormatSymbols().getDecimalSeparator()); //true

    formatter = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
    assertEquals(',', formatter.getDecimalFormatSymbols().getDecimalSeparator()); //true

    //and in case you want another decimal seperator for a specific locale
    DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
    decimalFormatSymbols.setDecimalSeparator('.');

    formatter.setDecimalFormatSymbols(decimalFormatSymbols);
    assertEquals('.', formatter.getDecimalFormatSymbols().getDecimalSeparator()); //true
}


If your NumberFormat instance is a DecimalFormat, then you can use getDecimalFormatSymbols() to get to that information.

In general, you can't get to that information.

Why do you need it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜