how do I change a string to double ?

how do I change a string to double ? thanks.
LVL 1
meow00Asked:
Who is Participating?
 
CEHJCommented:
double d = Double.parseDouble(s);
0
 
meow00Author Commented:
 but I don't have a Double ...

  I have :

  String a = "12.3";

 double b;

 how do I put a in b ?
0
 
CEHJCommented:
b = Double.parseDouble(a);
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
Mayank SAssociate Director - Product EngineeringCommented:
0
 
KriskraCommented:
Simplest use:

String myString = "12.3";
try {
   double myDouble = Double.parseDouble(myString);
} catch (NumberFormatException e) {
   //The string does not contain a double value...
}

Don't forget to import "NumberFormatException"...

Best regards,
KK
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> Don't forget to import "NumberFormatException"...

Not required as it is in java.lang
0
 
CEHJCommented:
More info on conversions, and testable, at

http://mindprod.com/applets/converter.html
0
 
nosturnCommented:
I'm sure you have the answer by now

You often have the situation where you want to convert a String representing a number to a primitive.

There are reference classes for each of the primitive types, and these provide static methods for converting
a String representing the number (like "12.0")  to the primitive - 12.0 ( A double)

So in answer to your question  "how do I put a in b ?" CEHJ is quite right, but you might not be aware
that you don't need any existing references as the conversion methods are static.

Java provides static String conversion methods for many of the primitive types, by the way :

 double d = Double.parseDouble("12");   //12.0
 float f = Float.parseFloat("12");            //12.0
 long l = Long.parseLong("12");             // 12
 int i =    Integer.parseInt("12");            // 12

 int i =    Integer.parseInt("12.0");            // throws a NumberFormatException (as KK said)
                                                         
Hope this helps
Andy


 



0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.