3

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?

0

2 Answers 2

6

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.

1
  • 1
    I added to the program now that it first sets the locale to US, now it's working fine. The locales were indeed different on the machines.
    – Batash
    Dec 24, 2015 at 17:12
2

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.