- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Java中是否有一个类可以让您将“102203345.32”之类的数字格式化为“102.203.345,32”并返回字符串类型?
我想获得一个字符串,其中千位由“.”分隔。小数点之间用逗号“,”分隔。
有人可以帮我吗?我找到了一个类 DecimalFormat 并尝试自定义它:
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") 我得到一个异常...
我应该做什么?
谢谢!
最佳答案
请务必阅读并理解 Javadoc 的特殊模式字符部分。 ,尤其是这个注释:
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.
如果您已经这样做了,您应该清楚您必须使用 the appropriate constructor并提供适当配置的分隔符/分组字符,而在模式本身中,点和逗号具有特殊含义。
实际上,上述所有复杂性都是为了您的方便:它允许您自定义数字格式并对其进行本地化。
这是一个对我有用的代码示例:
final DecimalFormatSymbols syms = new DecimalFormatSymbols();
syms.setDecimalSeparator(',');
syms.setGroupingSeparator('.');
DecimalFormat myFormatter = new DecimalFormat("###,###.00", syms);
System.out.println(myFormatter.format(1234.12));
您还可以使用应用本地化模式的变体,以获得更直观的代码:
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 - 如何在Java中将数字格式化为 "xxx.xxx.xxx,yy"形式的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22456350/
我是一名优秀的程序员,十分优秀!