【问题标题】:Java's DecimalFormat parses incorrect decimal number as integerJava DecimalFormat 将错误的十进制数解析为整数
【发布时间】:2020-03-24 07:45:28
【问题描述】:

收到所有问候。

我需要验证一个文本是否对应一个数字。项目语言环境是 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】:

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

    Locale defaultLocale = new Locale("es", "CO");
    Scanner scanner = new Scanner("1.48");
    scanner.useLocale(defaultLocale);
    Number number = scanner.nextDouble();
    

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      • 2012-03-08
      • 2011-04-08
      • 2023-03-25
      • 2020-04-25
      相关资源
      最近更新 更多