简体   繁体   English

Java 的 DecimalFormat 将不正确的十进制数解析为整数

[英]Java's DecimalFormat parses incorrect decimal number as integer

Receive all a greeting.收到大家的问候。

I need to validate that a text corresponds to a number.我需要验证一个文本对应一个数字。 The project locale is es_CO .项目语言环境是es_CO The problem I have now is that texts with a period used as a decimal separator are parsed to integer numbers, when it should be an error, since in the aforementioned location, the decimal separator is a comma.我现在遇到的问题是,使用句点作为小数分隔符的文本被解析为整数,当它应该是一个错误时,因为在上述位置,小数分隔符是一个逗号。

For example:例如:

  • Locale: es_CO语言环境: es_CO
  • Pattern: ###.###,##模式: ###.###,##
  • Text: 1.48文字: 1.48
  • Number result: 148.0结果数: 148.0

Source code:源代码:

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.

Thanks for any help you can give me.感谢你给与我的帮助。

That does seem to be a bug in DecimalFormat.这似乎是 DecimalFormat 中的一个错误。 One way to work around it is to use a Scanner :解决它的一种方法是使用Scanner

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM