Exercise:
Write a Java Program to convert double type variable to string.
1.Convert using Valueof()
Click Here to View the Solution!
public class DoubleToString {
public static void main(String[] args) {
double num1 = 21.88;
String str1 = String.valueOf(num1);
System.out.println(str1);
}
}
Click Here to View the Output!
21.88
Click Here to View the Explanation!
In this program, a variable of the type double
is converted to a String
variable using a String
class’ method valueOf()
. This is the most common method utilized for the conversion.
2.Convert using toString()
Click Here to View the Solution!
public class DoubleToString {
public static void main(String[] args) {
double num1 = 8.123;
String str1 = Double.toString(num1);
System.out.println(str1);
}
}
Click Here to View the Output!
8.123
Click Here to View the Explanation!
In this program, double
type variables are converted to String
type variables using a Double
(Java wrapper) class method toString()
.
3.Convert using format()
Click Here to View the Solution!
public class DoubleToString {
public static void main(String[] args) {
double num = 34.16;
String str = String.format("%f", num);
System.out.println(str);
}
}
Click Here to View the Output!
34.160000
Click Here to View the Explanation!
In this program, double
to string
variable conversion is taking place with the help of format()
method.