如何将 DecimalFormat 的小数点分隔符从逗号更改为点/点? [英] How to change the decimal separator of DecimalFormat from comma to dot/point?

查看:26
本文介绍了如何将 DecimalFormat 的小数点分隔符从逗号更改为点/点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个疯狂的小方法,可以将 BigDecimal 值转换为漂亮且可读的字符串.

I have this little crazy method that converts BigDecimal values into nice and readable Strings.

private String formatBigDecimal(BigDecimal bd){
    DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(3);
    df.setMaximumFractionDigits(3);
    df.setMinimumIntegerDigits(1);
    df.setMaximumIntegerDigits(3);
    df.setGroupingSize(20);
    return df.format(bd);
}

然而,它也会产生一个所谓的分组分隔符 "," 使我的所有值都像这样:

It however, also produces a so called grouping separator "," that makes all my values come out like this:

xxx,xxx

我确实需要分隔符是点或点,而不是逗号.有没有人知道如何完成这个小壮举?

I do need the separator to be a dot or a point and not a comma. Does anybody have a clue of how to accomplish this little feat?

我已阅读this,特别是this 现在要死了,但我找不到完成此操作的方法.我是否以错误的方式接近这个?有没有更优雅的方法来做到这一点?甚至可能是考虑不同本地数字表示的解决方案,因为按照欧洲标准,逗号将是完美的.

I have read this and in particular this to death now but I cannot find a way to get this done. Am I approaching this the wrong way? Is there a much more elegant way of doing this? Maybe even a solution that accounts for different local number representations, since the comma would be perfect by European standards.

推荐答案

您可以通过设置区域设置或使用 DecimalFormatSymbols.

You can change the separator either by setting a locale or using the DecimalFormatSymbols.

如果你希望分组分隔符是一个点,你可以使用欧洲语言环境:

If you want the grouping separator to be a point, you can use an european locale:

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;

或者,您可以使用 DecimalFormatSymbols 类来更改出现在由 format 方法生成的格式化数字中的符号.这些符号包括小数点分隔符、分组分隔符、减号和百分号等:

Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.'); 
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);

currentLocale 可以从 Locale.getDefault() 获得,即:

currentLocale can be obtained from Locale.getDefault() i.e.:

Locale currentLocale = Locale.getDefault();

这篇关于如何将 DecimalFormat 的小数点分隔符从逗号更改为点/点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆