Jorge Garcia
Jorge Garcia

Reputation: 65

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:

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.

Upvotes: 2

Views: 181

Answers (1)

VGR
VGR

Reputation: 44328

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();

Upvotes: 0

Related Questions