I've made a java application where i use DecimalFormat to format the output for numbers.
DecimalFormat df = new DecimalFormat("#.##");
return Double.parseDouble(df.format(costs));
It works fine on my computer, but when this code execuites on another machine, i get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "25,1"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
Both machines have the latest java version installed, both are windows 7. One machine is 64-bit, while the other is 32-bit though. What could be the reason for the error to be happening on the other machine only?
Locales, in a word. One machine is European format, #,#
and the other US/UK, #.#
.
Edit:
Use your DecimalFormat object to travel in both directions: df.parse(...)
parses the String created by df.format
.
df.format(25.1)
returns formatted number String
based on the default or specified locale.
i.e. for Locale.US
it will return String
25.1
while in case of Locale.ITALY
it will return 25,1
as decimal separators are different for both the locales.
Another problem is you are parsing the formatted String
to double
. If you have double
value (or something else which is valid number), then you don't need to format the number with DecimalFormat
.
If you have valid number String
(25.1
), you can parse it with DecimalFormatter
in following way,
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ITALY);
DecimalFormat df = (DecimalFormat) nf;
df.applyPattern("#.##");
try {
System.out.println(df.parse("25,1"));
} catch (ParseException e) {
e.printStackTrace();
}
OUTPUT
25.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With