How to convert double to String in Java

How to convert double to String in Java

Example:

Input:  num=1320.25
Output: "1320"

Approach: 1: Using toString()

Java


public class DoubleToString {
    public static void main(String[] args) {
        double num = 1320.25;
        String numStr = doubleToString(num);
        System.out.println("String is " + numStr);
    }

    private static String doubleToString(double num) {
        return Double.toString(num);
    }

}

Approach : 2: Using valueOf()

Java


public class DoubleToString {
    public static void main(String[] args) {
        double num = 1320.25;
        String numStr = doubleToString(num);
        System.out.println("String is " + numStr);
    }

    private static String doubleToString(double num) {
        return String.valueOf(num);
    }

}


No comments:

Post a Comment