Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DecimalFormat not working the same on other machine

Tags:

java

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?

like image 782
Batash Avatar asked Sep 02 '25 04:09

Batash


2 Answers

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.

like image 76
GKFX Avatar answered Sep 05 '25 01:09

GKFX


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
like image 25
akash Avatar answered Sep 04 '25 23:09

akash