Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
surlol Avatar asked Mar 26 '13 17:03

surlol


People also ask

How does parse double work?

The parseDouble() method of Java Double class is a built in method in Java that returns a new double initialized to the value represented by the specified String, as done by the valueOf method of class Double. Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed.

Can you parse a double in Java?

parseDouble() We can parse String to double using parseDouble() method. String can start with “-” to denote negative number or “+” to denote positive number.

How do you read a double scanner in Java?

nextDouble() method scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.

What scanner method returns a double value?

The nextDouble() method of java. util. Scanner class scans the next token of the input as a Double. If the translation is successful, the scanner advances past the input that matched.


1 Answers

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.

like image 162
s106mo Avatar answered Sep 28 '22 04:09

s106mo