Java Program to Convert Double to String
The primary goal to convert double to string is to store big streams of numbers that are coming where even data types fail to store the stream of numbers. It is generically carried out when we want to display the bigger values. Here it’s double in textfield GUI application because it becomes very easier for us to play with Java operations as everything is done in string format.
It becomes very crucial from the programmer’s perceptive as we will see often primitive datatypes being converted to string type as java is object-oriented focus on bringing closer to real-life because of which these conversions become very important.
Input: 22.098 // Double Data Output: 22.098 // String Data
Input: 123.456 // Double Data Output: 123.456 // String Data
Different Ways for Converting Double to String
There are different kinds of methods to convert double data to string data. Two standard approaches are as follows:
- Using valueOf() method of String class
- Using toString() method of Double class
Approach 1: Using valueOf() method of String class
valueOf() of String class is a method in Java that simply typecasts below-given parameters to strings always as it is an inbuilt method of String class in Java. Do remember always any execution after making one execution using this method may change the result as it will concatenate leading to unguided output.
int a = 10, int b = 20; String s1 = String.valueOf(a); String s2 = String.valueOf(b); System.out.println(s1+s2); || Output: 30 || Addition of a and b via s1+s2 System.out.println(s1+s2); || Output: 1020 || Concatenation of s1 & s2
Parameters: It can hold objects, float, char, double, int, float, long, and character array.
Return type: String
This method is an inbuilt method present already in the directory of java which returns the string object as discussed.
Approach 2: Using the toString() method of Double Class
In Java whenever a print is called, always toString() method of Object Class in java is always called be it directly or indirectly. Even if this inbuilt function is not used and the double number is getting printed then too toString() method is called. The string is a class in Java. All the classes in Java are derived from Object Class. Whenever print is accessed where an object in a Java program is not created. Whenever the user gives a print command in Java, the toString() method of the Object class in Java is always called.
So, now if the user has created an object of his own type then there is an urgency to override the existing toString() method so that when the print command is called overridden toString() method is called. If no object is created by the user then it is known it is already an inbuilt method present already in the directory of java which will convert the double data to the string value.