Parse string to double, return defaultValue if parse fails - Java java.lang

Java examples for java.lang:String Parse

Description

Parse string to double, return defaultValue if parse fails

Demo Code



public class Main{
    public static void main(String[] argv){
        String value = "java2s.com";
        double defaultValue = 42.45678;
        System.out.println(parseDouble(value,defaultValue));
    }//from   w w  w  . j  a v  a 2  s. c  o m
    /** Parse string to double, return defaultValue if parse fails */
    public static double parseDouble(String value, double defaultValue) {
        double parsed = defaultValue;
        if (value != null) {
            try {
                parsed = Double.parseDouble(value);
            } catch (NumberFormatException e) {
                parsed = defaultValue;
            }
        }
        return parsed;
    }
}

Related Tutorials