[英]Appending two decimal number strings and parse as double
I want to get the result 0.054563
from a String
and parse it as a double
. 我想从
String
获取结果0.054563
并将其解析为double
。 My current attempt looks like, 我目前的尝试看起来像,
String number1 = "54,563";
String number2 = "54,563";
String value = "0.0" + number1;
String value2 = "0.0" + number2;
Double rd1 = Double.parseDouble(value.replaceAll(",","."));
Double rd3 = Double.parseDouble(value2.replaceAll(",","."));
System.out.println(rd1);
However, when I run it, I get the following error: 但是,当我运行它时,我收到以下错误:
Exception in thread "main" java.lang.NumberFormatException: multiple points
线程“main”中的异常java.lang.NumberFormatException:多个点
You get the exception, because value
would be "0.054,563" and only one period is allowed in a double
literal like 0.1
. 你得到了例外,因为
value
将是“0.054,563”,并且在double
字面积中只允许一个句点,如0.1
。 Your code value.replaceAll(",",".")
just changes the value to 0.054.563
, which is still illegal because of the two periods. 您的代码
value.replaceAll(",",".")
只是将值更改为0.054.563
,由于这两个句0.054.563
,这仍然是非法的。 Remove the comma before like 之前删除逗号
String value = "0.0" + number1.replaceAll(",", "");
Then, you can use Double rd1 = Double.parseDouble(value)
without the additional replaceAll(...)
. 然后,您可以使用
Double rd1 = Double.parseDouble(value)
而无需额外的replaceAll(...)
。
I further strongly recommend you to do the conversion mathematically and not through String
conversions and parsing, since these are unnecessary and rather costly operations. 我进一步强烈建议您以数学方式进行转换,而不是通过
String
转换和解析,因为这些是不必要且相当昂贵的操作。
You could use a regular expression to remove all non-digits. 您可以使用正则表达式删除所有非数字。 The pattern
\\D
matches non-digits. 模式
\\D
匹配非数字。 Using a Pattern
is faster if you need to do this multiple times. 如果您需要多次执行此操作,则使用
Pattern
会更快。 So you could do something like, 所以你可以做点什么,
String number1 = "54,563";
Pattern p = Pattern.compile("\\D");
Matcher m = p.matcher(number1);
String number2 = "0.0" + m.replaceAll("");
System.out.println(Double.parseDouble(number2));
or if you only need to do it once, you could do it inline like 或者如果你只需要做一次,你可以像在线一样进行
String number1 = "54,563";
String number2 = "0.0" + number1.replaceAll("\\D", "");
System.out.println(Double.parseDouble(number2));
Both of which output your desired 两者都输出你想要的
0.054563
0.054563
Yeah, it's possible. 是的,这是可能的。 You gotta first change number1 to a string then do that + thing.
你必须首先将number1更改为字符串,然后执行该操作。
String value = "0.0" + Integer.toString(number1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.