Reputation: 21
Double.valueOf with comma decimal separator throws NumberFormatException. Java 1.7.0_67 and 1.8.0_25.
I also try to set DecimalFormatSymbols with "," as decimalSeparator.
Locale.setDefault(Locale.FRANCE);
assert "12,3".equals(NumberFormat.getInstance().format(12.3));
if (((DecimalFormat) NumberFormat.getInstance()).getDecimalFormatSymbols().getDecimalSeparator() == ',')
Double.valueOf("12,3");
Upvotes: 2
Views: 3590
Reputation: 1190
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("12,3");
Double d = number.doubleValue();
System.out.println(d);
Upvotes: 3
Reputation: 36703
Double.valueOf() is not Locale aware. It only understands numbers with dots as decimal places.
Luckily you can use the same NumberFormat instance for formatting and parsing which is Locale aware ....
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
System.out.println(format.format(12.3)); // ==> "12,3"
System.out.println(format.parse("12,3")); // ==> 12.3
Upvotes: 1
Reputation: 206816
Double.valueOf(String)
does not take the default locale into account. Note that the API documentation of the method explains exactly what format it expects. It also tells you this:
To interpret localized string representations of a floating-point value, use subclasses of NumberFormat.
Use, for example, DecimalFormat
instead to parse the string.
DecimalFormat format = new DecimalFormat("##.#");
Double value = (Double) format.parse("12,3");
Upvotes: 0