[英]Parsing double with comma as decimal separator
I get inputs from user and read it line by line.Then I'm using split method to tokenize the inputs. 我从用户那里获取输入并逐行阅读它,然后使用split方法将输入标记化。 Like this:
像这样:
Scanner input=new Scanner(System.in);
String input1=input.nextLine();
String[] tokens=input1.split(" ");
method1(Double.parseDouble(tokens[0]),Double.parseDouble(tokens[1]));
Here is method1
: 这是
method1
:
public static void method1 (double a, double b) {
System.out.println(a);
System.out.println(b);
}
When I declare 3.5 and 5.3 output; 当我声明3.5和5.3输出时;
3.5
5.3
Here there is no problem but if I declare 3,5 and 5,3 my code giving error in below; 这里没有问题,但是如果我在下面声明错误,则声明3,5和5,3;
Exception in thread "main" java.lang.NumberFormatException: For input string: "3,5"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
How can I fix this problem? 我该如何解决这个问题?
Using NumberFormat
you can do something like this: 使用
NumberFormat
可以执行以下操作:
NumberFormat f = NumberFormat.getInstance(Locale.FRANCE);
double myNumber = f.parse("3,5").doubleValue();
Now you can pass myNumber
to the method that accepts double
value. 现在,您可以将
myNumber
传递给接受double
myNumber
值的方法。
When using Locale.FRANCE
, you tell Java that you write double
numbers with ,
instead of .
当使用
Locale.FRANCE
,你告诉Java的,你写的double
数字用,
而不是.
. 。
You could use DecimalFormat
like this: 您可以这样使用
DecimalFormat
:
DecimanFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance());
Double returnValue = Double.valueOf(df.format(input1));
So DecimalFormatSymbols.getInstance()
will get the default locale and its correct symbols. 因此
DecimalFormatSymbols.getInstance()
将获取默认语言环境及其正确的符号。
Read More about DecimalFormat
. 阅读有关
DecimalFormat
更多信息。
what i guess is : your input via scaner is 我猜是:您通过扫描仪输入的是
3.5 5.3
and you have applied 你已经申请了
String[] tokens=input1.split(" ");
so it has divided your strings in to substrings ie 3.5 and 5.3 if you give your input as 因此,如果您输入的内容为,则将您的字符串分为子字符串,即3.5和5.3
3.5,5.3
It will be a success and it will compile without an error.. 这将是成功的并且它将编译而不会出现错误。
in your case 在你的情况下
input 3,5 5,3
it you just need to put a "," in split method like : 它只需要在拆分方法中放入“,”,例如:
String[] tokens=input1.split(",");
and it will work with output as .... 它将与...一起工作
3 3
5 5 5 5
3 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.