Reputation: 408
I am trying to create Double object from decimal string value where comma is floating separator.
Passing locale arguments to vm:
-Duser.country=BR
-Duser.language=PT
String value = "500,21";
Double dob = new Double(value);
Getting exception:
java.lang.NumberFormatException: For input string: "500,21" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224) at java.lang.Double.valueOf(Double.java:475) at java.lang.Double.(Double.java:567)
Upvotes: 2
Views: 2049
Reputation: 1489
It looks like that new Double(value)
does not take into consideration the locale setting.
The implementation ends up calling this method here and it is only looking for ".".
With the locale set as you did you can use this:
NumberFormat.getInstance().parse(value).doubleValue()
Here is a similar discussion.
Upvotes: 0
Reputation: 48404
You can try with a localized NumberFormat
:
String value = "500,21";
// replace the hard-coded Locale definition with your arguments, or
// Locale.getDefault(), etc.
NumberFormat nf = NumberFormat.getInstance(new Locale("pt", "BR"));
try {
Double d = nf.parse(value).doubleValue();
System.out.println(d);
}
catch (ParseException pe) {
// TODO
}
Output
500.21
Upvotes: 1