Method 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 e.g. If the string is 122.20ab
this exception will be thrown.
String str="122.202";
Double var= Double.parseDouble(str);
Double variable var value would be 122.202
after conversion.
Method 2: Using Double.valueOf
String str3="122.202";
Double var3= Double.valueOf(str3);
The value of var3
would be 122.202
.
Method 3: Double
class constructor
String str2="122.202";
Double var2= new Double(str2);
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.
Complete Example:
try{
//Using parseDouble
String str="122.202";
Double var= Double.parseDouble(str);
System.out.println(var);
String str2="122.202";
Double var2= new Double(str2);
System.out.println(var2);
//Using valueOf method
String str3="122.202";
Double var3= Double.valueOf(str3);
System.out.println(var3);
}catch (NullPointerException e){ e.printStackTrace();}
catch (NumberFormatException e){ e.printStackTrace();}
}
Output:
122.202
122.202
122.202
As additional, here's how to get the text from EditText
:
EditText et = (EditText) findViewById(R.id.myEditText);
String text = et.getText().toString();
Source.