如何在 Java 中将数字格式化为“xxx.xxx.xxx,yy"形式的字符串? [英] How to format numbers as strings to be in the form "xxx.xxx.xxx,yy"in Java?

查看:49
本文介绍了如何在 Java 中将数字格式化为“xxx.xxx.xxx,yy"形式的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 中是否有一个类可以让您将102203345.32"之类的数字格式化为102.203.345,32"并返回字符串类型?

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 ','.

有人可以帮我吗?我找到了一个类 DecimalFormat 并尝试对其进行自定义:

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

但是当我像这样调用 customFormat 方法时: CustomDecimalFormat.customFormat("###.###,00") 我得到一个异常...

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

我该怎么办?

谢谢!

推荐答案

请务必阅读并理解 Javadoc,特别是这个注释:

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

此处列出的字符用于非本地化模式.本地化模式使用取自此格式化程序的 DecimalFormatSymbols 对象的相应字符,而这些字符将失去其特殊状态.

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

这篇关于如何在 Java 中将数字格式化为“xxx.xxx.xxx,yy"形式的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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