如何指定小数分隔符

我有一个相当简单的问题。 我得到像6.03这样的实数输入,但这给了我错误。 如果我将它改为6,03 ,那没关系。 但是,我无法更改我需要处理的输入,因此如何告诉Java使用. 作为分隔符而不是,

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

谢谢

Scanner可以提供Locale使用,您需要指定使用的Locale . 作为小数分隔符:

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

您可能遇到了Locale问题。 您可以使用java.text.NumberFormat进行解析。

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

直接取自手册。

区域敏感格式

前面的示例为默认的Locale创建了一个DecimalFormat对象。 如果要为非默认语言环境使用DecimalFormat对象,则实例化NumberFormat,然后将其强制转换为DecimalFormat。 这是一个例子:

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

运行上一个代码示例将导致后面的输出。 格式化的数字位于第二列,因Locale而异:

 ###,###.### 123,456.789 en_US ###,###.### 123.456,789 de_DE ###,###.### 123 456,789 fr_FR