S
S
student_12021-10-31 19:23:33
Java
student_1, 2021-10-31 19:23:33

How to parse string to double?

There is a line: String str = " 80.00 ";
I want to parse it into double, but the compiler gives me an exception.
Question: What could be the problem?
the code:

String str = " 80.00 ";
double sum = Double.parse(str.trim());

Result:
java.lang.NumberFormatException: For input string: " 80.00 "
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal .java:110)
at java.base/java.lang.Double.parseDouble(Double.java:543)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2021-10-31
@sergey-gornostaev

Your virtual machine uses a locale in which the decimal part is separated by a comma instead of a dot.

R
rPman, 2021-10-31
@rPman

because it uses the system locale settings (different countries use different separators . or ,)
Choose a country with your format or ask users to enter numbers in the format accepted in their country (specified in the OS system locale)

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE); // Locale.US если надо точку, осторожно запятая с ним игнорируется как разделитель тысяч
Number number = format.parse("1,234");
double d = number.doubleValue();

ps I don't see any glitches with this dot.
Programmers in Russia are used to the dot, and the standard expects a comma.
for example, the sber application draws a comma on the screen, but you need to enter a dot for kopecks (the comma will give an error),
but the worst thing is when people climb into the windows locale settings and change the comma to a dot and get even more glitches with the same ms office

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question