Search code examples
javajava.util.scannerlocale

How exactly does Java Scanner parse double?


I'm using a Windows 7 machine whose "Control Panel\Clock, Language, and Region" is "Denmark"

According to the documentation for Scanner:

A scanner's initial locale is the value returned by the Locale.getDefault() method;

But when I run the code:

System.out.println(Locale.getDefault());
Scanner sc = new Scanner("1.0");
sc.nextDouble();

It outputs "en_US" and then throws a java.util.InputMismatchException at sc.nextDouble() . It works when the scanner is initialized with "1,0"

However, if I explicitly set the Locale:

Locale.setDefault(Locale.US);
System.out.println(Locale.getDefault());
Scanner sc = new Scanner("1.0");
sc.nextDouble();

It outputs "en_US" and then parses the double just fine. Am I missing something, or is the documentation for Scanner wrong?

Edit Following the suggestion of @Perception, I looked at sc.locale() in the first example. It prints "da_DK". So why is it not "en_US", when that is what is being returned by the Locale.getDefault() method?


Solution

  • There are two different Locale categories, one for display and one for format. The scanner uses Locale.getDefault(Locale.Category.FORMAT) but if you call Locale.getDefault() you get the locale for display. The setLocale(Locale) method sets both.