-2

I have the following String:

String p = "33,644.234";

How can I convert it to double value?

Following gives java.lang.NumberFormatException: For input string: "33,644.234"

System.out.println(Double.valueOf(p));

kindly suggest.

Baby
  • 5,062
  • 3
  • 30
  • 52
Anushree Acharjee
  • 854
  • 5
  • 15
  • 30
  • Remove the comma from it? – merlin2011 May 10 '14 at 04:47
  • no, i cant do it. I need the output double as 33,644.234 – Anushree Acharjee May 10 '14 at 04:50
  • @AnushreeAcharjee, See the update to my answer if you want to `print` the double in that format. – merlin2011 May 10 '14 at 04:53
  • thanks merlin2011. If I want the output type as double, not String, is there any way out? – Anushree Acharjee May 10 '14 at 05:01
  • The true form of a `double` in the computer is stored as a bunch of bits. Java's default way of printing doubles does not provide the `,`, which is why we need to use `String.format` to display it in a certain way. – merlin2011 May 10 '14 at 05:09
  • Note also that, when you call `System.out.println`, you are implicitly converting the `double` into a `String` to display it at all. The `double` itself does not have an inherent format. – merlin2011 May 10 '14 at 05:10
  • actually in my program I wont be using the output in System.out.println, rather I have to pass it to JAXRS. If I store the variable as String, in the REST response it shows as distance:"33,644.234". I was looking for an way if I can make it distance: 33,644.234 – Anushree Acharjee May 10 '14 at 05:15
  • I am not familiar with `JAXRS`, but I can tell you that if you store it as a double, you will most likely not be able to force it to show the comma, unless `JAXRS` gives you a way of specifying display and parsing for `double` values. – merlin2011 May 10 '14 at 05:21

1 Answers1

5

Remove the comma and then parse it.

 double d = Double.parseDouble(p.replace(",",""));

Based on the OP's update, he wants the double to print in the original form, with the comma. The answer to that comes from this question.

System.out.println(String.format("%1$,.2f", d));

Output:

33,644.23
Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329