How to specify decimal delimiter

2019-03-05 15:54发布

I have a fairly simple problem. I am getting real-number input like6.03, but that gives me errors. If I change it to 6,03, it's ok. I, however, can't change the input I need to process, so how do I tell Java to use . as the delimiter instead of ,?

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

Thanks

3条回答
太酷不给撩
2楼-- · 2019-03-05 16:05

Taken directly from the manual.

Locale-Sensitive Formatting

The preceding example created a DecimalFormat object for the default Locale. If you want a DecimalFormat object for a nondefault Locale, you instantiate a NumberFormat and then cast it to DecimalFormat. Here's 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());

Running the previous code example results in the output that follows. The formatted number, which is in the second column, varies with Locale:

###,###.###      123,456.789     en_US
###,###.###      123.456,789     de_DE
###,###.###      123 456,789     fr_FR
查看更多
聊天终结者
3楼-- · 2019-03-05 16:18

You're probably running into Locale 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();
查看更多
相关推荐>>
4楼-- · 2019-03-05 16:20

Scanner can be provided with Locale to use, you need to specify Locale that uses . as decimal separator:

Scanner sc = new Scanner(System.in).useLocale(Locale.ENGLISH); 
查看更多
登录 后发表回答