gpt4 book ai didi

java - 如何在Java中将数字格式化为 "xxx.xxx.xxx,yy"形式的字符串?

转载 作者:行者123 更新时间:2023-12-01 18:34:52 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com