Ero Stefano
Ero Stefano

Reputation: 646

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?

Upvotes: 2

Views: 4594

Answers (2)

Phanindra mallela
Phanindra mallela

Reputation: 1

String cannot be converted to double

return String.format("%.5f",area);

I found this error while I was running my program. It means my program needs an output in double datatype but the above error returns the string datatype so now we need to convert the string to double. For this, we use the below methods

Double.parseDouble(String.format("%.5f",area));
Double.valueOf(String.format("%.5f",area));

Upvotes: 0

Hakanai
Hakanai

Reputation: 12670

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.

Upvotes: 4

Related Questions