How to convert double to String in Java
How to Convert double to String in Java
It is used when we want to convert double primitive to String type. There are two methods to convert double to String.
- Using String.valueOf() method
- Using Double.toString() method
Using String.valueOf() method
You can convert double primitive to String by calling the valueOf() method of String class. String.valueOf() is an overloaded method. It returns the String representation of the double argument. The signature of the method is given below:
public static String valueOf(double d)
Example
In this example, we have a variable sum of type double that contains value 34.22. str is a variable of type String that stores the converted value of sum. The String is a class. The valueOf () is a method of String class which parses sum as an argument. The println statement prints the converted value of the variable sum.
public class DoubletoStringExample { public static void main(String args[]) { double sum=34.22; String str=String.valueOf(sum); System.out.println("After conversion value of sum is: "+str); } }
Output
After conversion value of sum is: 34.22
Using Double.toString() method
It also converts double to String. It is the static method of Double class. The signature of the method is given below:
public static String toString(double d)
Example
In this example, we have a variable pi of type double that contains value 3.141. val is a variable of type String that stores the converted value of pi. The Double is a wrapper class. The toString() is a method of Double wrapper class parses an argument pi of double type. The println statement prints the converted value of the variable pi.
public class DoubletoStringExample1 { public static void main(String args[]) { double pi=3.141; String val=Double.toString(pi); System.out.println("After conversion value of pi is: "+val); } }
Output
After conversion value of pi is: 3.141