简体   繁体   中英

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 . 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

You get the exception, because value would be "0.054,563" and only one period is allowed in a double literal like 0.1 . Your code value.replaceAll(",",".") just changes the value to 0.054.563 , which is still illegal because of the two periods. Remove the comma before like

String value = "0.0" + number1.replaceAll(",", "");

Then, you can use Double rd1 = Double.parseDouble(value) without the additional 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.

You could use a regular expression to remove all non-digits. The pattern \\D matches non-digits. Using a Pattern is faster if you need to do this multiple times. 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

Yeah, it's possible. You gotta first change number1 to a string then do that + thing.

 String value = "0.0" + Integer.toString(number1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM