Search code examples
javastringdoublestring-conversion

JAVA double to string format


Suddenly I get an error which before I didnt have

Example:

Double double1 = 0.12;
String string1 = String.format("%.2f", double1)

System.out.println(string1);

Output:

0,12

Then I do this

double double2 = Double.parseDouble(string1);

Error

java.lang.NumberFormatException: For input string: "0,12"

I'm pretty sure I comes because of the "," (comma). The funny thing is that two days ago anything was working fine and I didnt change anything.

Do know what happened or what I need to change?


Solution

  • Double#parseDouble parses numbers in the format out put by Double#toString.

    String#format, when asked to format a number with a decimal point, will output this in the current locale, but Double#toString will not.

    If you want to parse the output of String#format, I believe that Scanner can do this. Personally, though, I would avoid localisation in numbers you expect to parse, and either use Double#toString to do the formatting, or explicitly pass Locale.ROOT when formatting it.