Java Double toString() example

In this guide, you will learn about the Double toString() method in Java programming and how to use it with an example.

1. Double toString() Method Overview

Definition:

The toString() method of the Java Double class returns a string representation of the specified double value.

Syntax:

1. String Double.toString(double d) 
2. String doubleValue.toString()

Parameters:

For the static method:

double d: The double value to be converted to a string.

For the instance method:

There are no parameters as the method will return the string representation of the object's value.

Key Points:

- The resulting string will contain one digit in the least significant digit of the integral part and at least one digit in the fractional part.

- This method can handle and represent both regular floating-point numbers and numbers in scientific notation.

- There are two variants: a static method that takes a double as a parameter, and a non-static (instance) method that operates on the instance's value.

2. Double toString() Method Example

public class ToStringExample {
    public static void main(String[] args) {
        // Using static method
        double num = 123.45;
        String strValue = Double.toString(num);
        System.out.println("String representation using static method: " + strValue);

        // Using instance method
        Double doubleInstance = 456.78;
        String instanceStrValue = doubleInstance.toString();
        System.out.println("String representation using instance method: " + instanceStrValue);
    }
}

Output:

String representation using static method: 123.45
String representation using instance method: 456.78

Explanation:

In the provided example, the static toString() method of the Java Double class is used to convert the double value 123.45 into its string representation. 

Next, the non-static (instance) toString() method is demonstrated, where an instance of the Double class holding the value 456.78 is converted to its string representation. Both methods effectively transform a double value into its equivalent string format.

Comments