When I try to read the string "3.14" as a float using German Locale I expect one of two things to happen:
(1) throw an error, because that is not a valid way to write 3.14 in German
(2) fallback to a more standard decimal notation and read the number as 3.14 because that is what any German would read in that number
But instead I am getting 314.
import java.text.NumberFormat;
import java.util.Locale;
public class MyClass {
public static void main(String args[]) throws Exception {
System.out.println(
NumberFormat.getNumberInstance(Locale.GERMANY).parse("3.14")
); // prints 314
}
}
The oracle-documentation for parse states:
Number parse(String source)
Parses text from the beginning of the given string to produce a number.
Which does not really explain what I am seeing here as it doesn't specify any non-happy path. What is the javas understanding of a German decimal number, and how can I fail-fast and safely convert Strings to numbers assuming a German decimal notation?
The problem that you're facing is because the . is considered the grouping separator in the German locale:
The previous image is extracted from the DecimalFormat.java class
After that, if the parse finds the grouping character is just ignoring it:
Before you ask,
sawDecimalisfalseand the backup is initially -1 at the start of the loop and -1 when the next digit 1 is found. So,backup = position; is not doing anything.