Java的DecimalFormat将错误的十进制数解析为整数

问题描述 投票:2回答:1

收到所有问候。

我需要验证文本是否与数字相对应。项目区域设置为es_CO。我现在遇到的问题是,当使用句点作为小数点分隔符的文本被解析为整数时,这应该是一个错误,因为在上述位置,小数点分隔符是逗号。

例如:

  • 区域设置:es_CO
  • 模式:###.###,##
  • 文本:1.48
  • 数字结果:148.0

源代码:

Locale defaultLocale = new Locale("es", "CO");
NumberFormat numberFormat = NumberFormat.getNumberInstance(defaultLocale);
DecimalFormat decimalFormat = (DecimalFormat) numberFormat;
decimalFormat.applyLocalizedPattern("###.###,##");
Number number = decimalFormat.parse("1.48"); // Here I would expect an exception to be generated.

感谢您能给我任何帮助。

java formatting format decimalformat
1个回答
0
投票

这似乎是DecimalFormat中的错误。解决它的一种方法是使用Scanner

Locale defaultLocale = new Locale("es", "CO");
Scanner scanner = new Scanner("1.48");
scanner.useLocale(defaultLocale);
Number number = scanner.nextDouble();
© www.soinside.com 2019 - 2024. All rights reserved.