How to convert String to double in Java

How to convert String to double in Java

Example:

Input:  num="1320.25"
Output: 1320.25

Approach: 1 : Using parseDouble()

Java


public class StringToDouble {
    public static void main(String[] args) {
        String num = "1320.25";
        double numDouble = stringToDouble(num);
        System.out.println("Double is " + numDouble);
    }

    private static double stringToDouble(String num) {
       return Double.parseDouble(num);
    }

}


Approach : 2: Using valueOf()

Java


public class StringToDouble {
    public static void main(String[] args) {
        String num = "1320.25";
        double numDouble = stringToDouble(num);
        System.out.println("Double is " + numDouble);
    }

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

}


No comments:

Post a Comment