English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn how to convert a string variable to double in Java.
class Main { public static void main(String[] args) { //Create a string variable String str1 = "23"; String str2 = "456.6"; //Convert string to double precision //Using parseDouble() double num1 = Double.parseDouble(str1); double num2 = Double.parseDouble(str2); // Print double values System.out.println(num1); // 23.0 System.out.println(num2); // 456.6 } }
In the above example, we use the parseDouble() method of the Double class to convert the string variable to double.
Here, Double is a wrapper class in Java. For more information, please visitJava Wrapper Classes.
NoteThe value of the string variable should be a number. Otherwise, the compiler will throw an exception. For example,
class Main { public static void main(String[] args) { //Create a string variable String str1 = "w3codebox"; //Not a number, but a string value // Convert string to double precision // Using parseDouble() double num1 = Double.parseDouble(str1); //Print Double Precision Value System.out.println(num1); // throws NumberFormatException } }
We can also use the valueOf() method to convert a string variable to a double precision type variable. For example,
class Main { public static void main(String[] args) { //Create a string variable String str1 = "6143"; String str2 = "21312"; //Convert String to Double //Using valueOf() double num1 = Double.valueOf(str1); double num2 = Double.valueOf(str2); //Print Double Precision Value System.out.println(num1); // 6143.0 System.out.println(num2); // 21312.0 } }
In the above example, the valueOf() method of the Double class converts the string value to double.
Here, the valueOf() method actually returns an object of the Double class. However, the object will automatically be converted to the primitive type. In Java, this is called unboxing. For more information, please visitJava Auto-boxing and Unboxing.
That is,
//valueOf() returns a Double object //object to double precision double num1 = Double obj = Double.valueOf(str1);
class Main { public static void main(String[] args) { //Create a string variable String str = "614,33"; //Replace , with . str = str.replace(",", "."); //Convert String to Double //Using valueOf() double value = Double.parseDouble(str); //Print Double Precision Value System.out.println(value); // 614.33 } }
In the above example, we created a string named str. Note this line,
str = str.replace(",", ".");
Here, the replace() method usesDot (.)Replace the string withComma (,).For more information on replacing characters, please visitJava String replace().
Then, we use the parseDouble() method to convert the string to double.