3

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

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • What exactly are you trying to do? Do you just want to parse a number and then divide by `1e6`? Why are you performing numeric manipulations using strings? That's never going to work out well. – Daniel Pryden Dec 11 '16 at 03:47
  • Possible duplicate of [What is a NumberFormatException and how can I fix it?](http://stackoverflow.com/questions/39849984/what-is-a-numberformatexception-and-how-can-i-fix-it) – xenteros Dec 14 '16 at 05:48

3 Answers3

4

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.

thatguy
  • 21,059
  • 6
  • 30
  • 40
3

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

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

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

 String value = "0.0" + Integer.toString(number1);
Nick Ziebert
  • 1,258
  • 1
  • 9
  • 17