Javas DecimalFormat:如何拒绝“无效”格式输入分组小数?
使用以下 NumberFormat 时:
NumberFormat amountFormat = NumberFormat
.getNumberInstance(I18N.getThreadLocale());
amountFormat.setMaximumFractionDigits(2);
amountFormat.setMinimumFractionDigits(2);
解析时得到以下结果
System.out.println(amountFormat.parse(value));
- 通过10,50 => 1050
- 10,5 => 105
- 0,25 => 25
我知道在 Locale.ENGLISH 中“,”是组分隔符。但我认为上述结果没有意义。我们的客户对这种格式感到很奇怪。
如何禁用此分组?
我希望得到以下结果:
- 10,50 =>解析异常
- 10,5 =>解析异常
- 0,25 => ParseException
有标准方法可以做到这一点吗?或者我必须编写自己的 NumberFormat 吗?
When using the following NumberFormat:
NumberFormat amountFormat = NumberFormat
.getNumberInstance(I18N.getThreadLocale());
amountFormat.setMaximumFractionDigits(2);
amountFormat.setMinimumFractionDigits(2);
I get the following results when parsing via
System.out.println(amountFormat.parse(value));
- 10,50 => 1050
- 10,5 => 105
- 0,25 => 25
I know that in Locale.ENGLISH the "," is the group separator. But I don't think that the above results make sense. And our customers get weird about this formatting.
How can I disable this grouping?
I would like to have the following results:
- 10,50 => ParseException
- 10,5 => ParseException
- 0,25 => ParseException
Is there a standard way to do this? Or do I have to program my own NumberFormat?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
其中一个问题是分组字符(英语语言环境中的“,”)。要禁用对 NumberFormat 实例的分组支持,您只需调用 setGroupingUsed(false) 即可。
然而,这会导致一个不同的问题,即 NumberFormat 从字符串的开头进行解析,直到到达未知字符。如果禁用分组,parse("12foo") 将返回 12,就像 parse("10,50") 将返回 10 一样。要检查整个输入字符串是否已实际解析,您必须使用带有 ParsePosition 参数的解析方法并检查其索引以及输入字符串是否已解析到末尾或者解析器是否停止在字符串中的较早位置。
One problem is the grouping character (',' in an English locale). To disable grouping support for the NumberFormat instance, you can simply invoke setGroupingUsed(false).
This however, leads to a different problem, namely that NumberFormat parses from the beginning of the string, until it reaches an unknown character. parse("12foo") will return 12, just as parse("10,50") will return 10 if grouping is disabled. To check if the entire input string was actually parsed, you have to use the parse methods with a ParsePosition argument and check its index and if the input string was parsed to the end or if the parser stopped at an earlier position in the string.