String to Double in Java
In this lecture we will see the String to Double conversion. There are three ways to convert a String into a double.
1: Using Double.parseDouble
public static double parseDouble(String str) throws NumberFormatException
It returns the
double
value represented by the string argument and throws following exceptions:NullPointerException
– if the specified String str is null.NumberFormatException
– if the string format is not valid. For exampleIf the string is “122.20ab” this exception will be thrown.
String strg="222.102"; Double var= Double.parseDouble(str);
Double variable var value would be 222.102 after conversion.
2: Using Double.valueOf
String strg1="222.102"; Double var1= Double.valueOf(strg1);
The value of var1 would be 222.102
3: Double class constructor
String strg2="222.102"; Double var2= new Double(strg2);
Double class has a constructor which parses the passed String argument and returns a double value.
public Double(String s) throws NumberFormatException
Constructs a newly allocated
Double
object that represents the floating-point value of type double
represented by the string.Example:
public class Example{ public static void main(String args[]){ //Using parseDouble String strg="222.102"; Double var= Double.parseDouble(strg); System.out.println(var); String strg1="222.102"; Double var1= new Double(strg1); System.out.println(var1); //Using valueOf method
String strg2="122.202"; Double var2= Double.valueOf(strg2); System.out.println(var2); } }
Output:
122.202 122.202 122.202
Comments
Post a Comment