简体   繁体   中英

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 . 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
  • Pattern: ###.###,##
  • Text: 1.48
  • Number result: 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. One way to work around it is to use a Scanner :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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