Java double number to string

How to convert double to String in Java [Practical Examples]

In java, double is a primitive data type whereas Double is a wrapper class. As we know that java supports auto-boxing, so we can use double and Double interchangeably in most of the cases.

In several applications, we may need to convert a number to a string because we need to operate on the value in its string form. In many GUI based application also, if we have to display double value in text field we may need to convert. There are several ways to convert double type data to a string.

The list below shows eight different ways in which we can convert double to string.

  • Using + operator
  • Using String.valueOf()
  • Using Double.toString()
  • Using DecimalFormat class
  • Using String.format()
  • Using StringBuilder class
  • Using StringBuffer class
  • Using Double constructor

Using + operator

This is the simplest approach for converting double to a string. Here, we are using a concatenation operator + to store the double value as a string.
Example : In this example, we concatenate blank string «» with double variable d.

// Program to convert double to string in Java public class Main < public static void main(String[] args) < // Initializing the variable double d = 858.4854; // Converting double to string String s = d + ""; // Printing both the variables System.out.println("The value of double variable is " + d); System.out.println("The value of String variable is " + s); >> 
The value of double variable is 858.4854 The value of String variable is 858.4854 

Using String.valueOf()

In this approach, we are using valueOf method of String class that converts values passed as a parameter into a string.

Читайте также:  Test python version in script

Example : In this example, double variable d is converted to string using valueOf method.

// Program to convert double to string in Java public class Main < public static void main(String[] args) < // Initializing the variable double d = 858.4854; // Converting double to string String s = String.valueOf(d); // Printing both the variables System.out.println("The value of double variable is " + d); System.out.println("The value of String variable is " + s); >> 
The value of double variable is 858.4854 The value of String variable is 858.4854 

Using Double.toString()

In this approach, we are using Double class to convert double value to a string. Each of the Number subclasses includes a class method, toString() , that will convert its primitive type to a string.

Example :In this example, we are using toString method of Double class for conversion.

// Program to convert double to string in Java public class Main < public static void main(String[] args) < // Initializing the variable double d = 858.4854; // Converting double to string String s = Double.toString(d); // Printing both the variables System.out.println("The value of double variable is " + d); System.out.println("The value of String variable is " + s); >> 
The value of double variable is 858.4854 The value of String variable is 858.4854 

Using DecimalFormat class

In this approach, we are using the DecimalFormat class to convert double to String. Moreover, we can also get string representation with specified decimal places and rounding up the double number.

Example :In this example, we are using format method of DecimalFormat class for conversion. Here, we are also rounding up a double number to two digits and then converting to string.

import java.text.DecimalFormat; // Program to convert double to string in Java public class Main < public static void main(String[] args) < // Initializing the variable double d = 858.48549; // Converting double to string DecimalFormat df = new DecimalFormat(); String s1 = df.format(d); df = new DecimalFormat("#.0#"); String s2 = df.format(d); // Printing both the variables System.out.println("The value of double variable is " + d); System.out.println("The value of String variable s1 is " + s1); System.out.println("The value of String variable s2 is " + s2); >> 
The value of double variable is 858.4854 The value of String variable s1 is 858.485 The value of String variable s2 is 858.49 

Using String.format()

In this approach, we are using format method of a String class to convert double to string.

Example : In this example, we will use the access specifier » %f » as the value to format is a double type.

// Program to convert double to string in Java public class Main < public static void main(String[] args) < // Initializing the variable double d = 858.4854; // Converting double to string String s = String.format("%f", d); // Printing both the variables System.out.println("The value of double variable is " + d); System.out.println("The value of String variable is " + s); >> 
The value of double variable is 858.4854 The value of String variable is 858.485400 

Using StringBuilder class

In this approach, we are using append method of StringBuilder class. The append() method is used to append the string representation of the double argument to this sequence.

Example : In this example, we will use the append() method to add double value and toString() method to convert it to string.

// Program to convert double to string in Java public class Main < public static void main(String[] args) < // Initializing the variable double d = 858.4854; // Converting double to string StringBuilder b = new StringBuilder(); String s = b.append(d).toString(); // Printing both the variables System.out.println("The value of double variable is " + d); System.out.println("The value of String variable is " + s); >> 
The value of double variable is 858.4854 The value of String variable is 858.4854 

Using StringBuffer class

In this approach, we are using append method of StringBuffer class. The append() method is used to append the string representation of the double argument to this sequence.

Example : In this example, we will use the append() method to add double value and toString() method to convert it to string.

// Program to convert double to string in Java public class Main < public static void main(String[] args) < // Initializing the variable double d = 858.4854; // Converting double to string StringBuffer b = new StringBuffer(); String s = b.append(d).toString(); // Printing both the variables System.out.println("The value of double variable is " + d); System.out.println("The value of String variable is " + s); >> 
The value of double variable is 858.4854 The value of String variable is 858.4854 

Using Double Constructor

In this approach, we are using constructor of double class to initialize with double value and then use toString() method to convert double object to the string. Although, this approach is deprecated from Java version 9, it can be used in the older versions.

Example : In this example, we will use the access specifier » %f » as the value to format is a double type.

// Program to convert double to string in Java public class Main < public static void main(String[] args) < // Initializing the variable double d = 858.4854; // Converting double to string Double o = new Double(d); String s = o.toString(); // Printing both the variables System.out.println("The value of double variable is " + d); System.out.println("The value of String variable is " + s); >>
Note: Main.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. The value of double variable is 858.4854 The value of String variable is 858.4854

Summary

The knowledge of converting double value to a String in Java is very useful while working on real time applications. In this tutorial, we covered eight different approaches to convert double to String in Java. As per the requirement of an application, we can choose an appropriate approach for conversion. We learned in detail about this approaches with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on conversion of double value to a string object in Java.

References

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

Java Tutorial

  • Set Up Java Environment
    • Set Up Java on Linux
    • Set up Java with BlueJ IDE
    • Set up Java with VSC IDE
    • Set up Java with Eclipse IDE
    • Java Multiline Comments
    • Java Variables
    • Java Global Variables
    • Java Date & Time Format
    • Different Java Data Types
    • Java Booleans
    • Java Strings
    • Java Array
    • Java Byte
    • Java convert list to map
    • Java convert double to string
    • Java convert String to Date
    • Java convert Set to List
    • Java convert char to int
    • Java convert long to string
    • Java Operators Introduction
    • Java Boolean Operators
    • Java Relational Operators
    • Java Arithmetic Operators
    • Java Bitwise Operators
    • Java Unary Operators
    • Java Logical Operators
    • Java XOR (^) Operator
    • Java Switch Statement
    • Java If Else Statement
    • Java While Loop
    • Java For / For Each Loop
    • Java Break Continue
    • Java Nested Loops
    • Java throw exception
    • Java Try Catch
    • Java Accessor and Mutator Methods
    • Java main() Method
    • IndexOf() Java Method
    • Java ListIterator() Method
    • Java create & write to file
    • Java read file
    • Java Parameter
    • Java Argument
    • Java Optional Parameters
    • Java Arguments vs Parameters
    • Java Arrays.asList
    • Java HashSet
    • Java Math
    • Java HashMap vs Hashtable vs HashSet
    • Java LinkedList
    • Linked List Cycle
    • Java List vs LinkedList
    • Java ArrayList vs LinkedList

    Источник

    Java Convert double to String

    Java Convert double to String

    While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

    Today we will see different ways to convert double to string in java. Java double to string conversion can be done in many ways, we will go through them one by one with example code snippets.

    Java Convert Double to String

    java convert double to string, java double to string

    Let’s look at different code snippets for java double to string conversion. Note that double is a primitive data type whereas Double is an Object. However java supports autoboxing, so they both can be used interchangeably in most of the cases.

    Using + operator

    double d = 123.45d; String str = d+""; // str is '123.45' 

    Double.toString()

    We can use Double class toString method to get the string representation of double in decimal points. Below code snippet shows you how to use it to convert double to string in java.

    double d = 123.45d; String str = Double.toString(d); System.out.println(str); //prints '123.45' 

    String.valueOf()

    double d = 123.456d; String str = String.valueOf(d); // str is '123.456' 

    new Double(double l)

    double d = 123.45d; //deprecated from Java 9, use valueOf for better performance String str = new Double(d).toString(); System.out.println(str); 

    String.format()

    double d = 36.98d; String s = String.format("%f", d); System.out.println(s); //36.980000 

    DecimalFormat

    We can use DecimalFormat class to convert double to String. We can also get string representation with specified decimal places and rounding of half-up.

    double d = 123.454d; String str = DecimalFormat.getNumberInstance().format(d); System.out.println(str); //str is '123.454' //if you don't want formatting str = new DecimalFormat("#.0#").format(d); // rounded to 2 decimal places System.out.println(str); //str is '123.45' str = new DecimalFormat("#.0#").format(123.456); // rounded to 2 decimal places System.out.println(str); //str is '123.46' 

    StringBuilder, StringBuffer

    double d = 123.45d; String str = new StringBuilder().append(d).toString(); 

    Java Double to String Example

    Here is a simple program where we will convert double to string and print it using all the different methods we saw above.

    package com.journaldev.string; import java.text.DecimalFormat; public class JavaDoubleToString < public static void main(String[] args) < double d = 123.45d; String str = Double.toString(d); System.out.println(str); str = String.valueOf(d); System.out.println(str); // deprecated from Java 9, use valueOf for better performance str = new Double(d).toString(); System.out.println(str); str = String.format("%f", d); System.out.println(str); //123.450000 str = d + ""; System.out.println(str); str = DecimalFormat.getNumberInstance().format(d); System.out.println(str); str = new DecimalFormat("#.0#").format(d); System.out.println(str); str = new StringBuilder().append(d).toString(); System.out.println(str); >> 

    That’s all for converting double to string in java program. Reference: Double API Doc

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Источник

    Converting Between Numbers and Strings

    Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.

    The Number subclasses that wrap primitive numeric types ( Byte , Integer , Double , Float , Long , and Short ) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:

    public class ValueOfDemo < public static void main(String[] args) < // this program requires two // arguments on the command line if (args.length == 2) < // convert strings to numbers float a = (Float.valueOf(args[0])).floatValue(); float b = (Float.valueOf(args[1])).floatValue(); // do some arithmetic System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); >else < System.out.println("This program " + "requires two command-line arguments."); >> >

    The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:

    a + b = 91.7 a - b = -82.7 a * b = 392.4 a / b = 0.0516055 a % b = 4.5

    Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat() ) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:

    float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);

    Converting Numbers to Strings

    Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:

    int i; // Concatenate "i" with an empty string; conversion is handled for you. String s1 = "" + i;
    // The valueOf class method. String s2 = String.valueOf(i);

    Each of the Number subclasses includes a class method, toString() , that will convert its primitive type to a string. For example:

    int i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);

    The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point:

    public class ToStringDemo < public static void main(String[] args) < double d = 858.48; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(dot + " digits " + "before decimal point."); System.out.println( (s.length() - dot - 1) + " digits after decimal point."); >>

    The output of this program is:

    3 digits before decimal point. 2 digits after decimal point.

    Источник

Оцените статью