English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn how to convert a double type variable to a string in Java.
class Main { public static void main(String[] args) { //Create a double type variable double num1 = 36.33; double num2 = 99.99; //to convert double to string //using valueOf() String str1 = String.valueOf(num1); String str2 = String.valueOf(num2); //Print string variable System.out.println(str1); // 36.33 System.out.println(str2); // 99.99 } }
In the above example, we used the valueOf() method of the String class to convert a double variable to a string.
Note:This is the best way to convert a double variable to a string in Java.
We can also use the toString() method of the Double class to convert a double variable to a string. For example,
class Main { public static void main(String[] args) { //Create a double type variable double num1 = 4.76; double num2 = 786.56; //to convert double to string //using toString() method String str1 = Double.toString(num1); String str2 = Double.toString(num2); // print string variables System.out.println(str1); // 4.76 System.out.println(str2); // 786.56 } }
Here, we use the toString() method of the Double class to convert a double variable to a string.
Here, Double is a wrapper class in Java. For more information, please visit Java Wrapper Classes.
class Main { public static void main(String[] args) { //Create a double type variable double num1 = 347.6D; double num2 = 86.56D; //to convert double to string // use + symbols String str1 = "" + num1; String str2 = "" + num2; // print string variables System.out.println(str1); // 347.6 System.out.println(str2); // 86.56 } }
Note this line,
String str1 = "" + num1;
Here, we use string concatenation operations to convert the double variable to a string. For more information, please visitJava String Concatenation.
class Main { public static void main(String[] args) { //Create a double type variable double num = 99.99; //Convert double to string using format() String str = String.format("%f", num); System.out.println(str); // 99.990000 } }
Here, we use the format() method to format a specified double variable into a string. For more information on formatting strings, please visitJava String format().