How to specify a decimal separator

I have a pretty simple problem. I get input with a real number, like 6.03 , but that gives me errors. If I change it to 6,03 , that's fine. However, I cannot change the input that I need to process, so how can I tell what Java uses . as a separator instead,?

 Scanner sc = new Scanner(System.in); double gX = sc.nextDouble(); // Getting errors 

thanks

0
source share
3 answers

Scanner can be provided by Locale for use, you need to specify the Locale that uses . as a decimal separator:

 Scanner sc = new Scanner(System.in).useLocale(Locale.ENGLISH); 
+4
source

You have probably encountered language issues. You can use java.text.NumberFormat for parsing.

 NumberFormat format = NumberFormat.getInstance(Locale.US); Number number = format.parse("6.03"); double d = number.doubleValue(); 
+1
source

Taken directly from the manual.

Local sensitive formatting

In the previous example, a DecimalFormat object was created for the default locale. If you need a DecimalFormat object for an unlimited locale, you create an instance of NumberFormat and then pass it to DecimalFormat. Here is an example:

 NumberFormat nf = NumberFormat.getNumberInstance(loc); DecimalFormat df = (DecimalFormat)nf; df.applyPattern(pattern); String output = df.format(value); System.out.println(pattern + " " + output + " " + loc.toString()); 

Execution of the previous code example leads to the following result. The formatted number, which is in the second column, depends on the language:

 ###,###.### 123,456.789 en_US ###,###.### 123.456,789 de_DE ###,###.### 123 456,789 fr_FR 
+1
source

Source: https://habr.com/ru/post/1482904/


All Articles