Java String to Double asDouble(final String str, final double def)

Here you can find the source of asDouble(final String str, final double def)

Description

Parse string to double, if string can't be parsed to double, then it will return given default value.

License

Open Source License

Parameter

Parameter Description
str string to parse
def default value.

Return

parsed value or default value.

Declaration

public static double asDouble(final String str, final double def) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from ww  w  .  j a  v a 2  s .  c  om
     * Parse string to double, if string can't be parsed to double, then it will return null.
     *
     * @param str string to parse
     *
     * @return parsed value or null.
     */
    public static Double asDouble(final String str) {
        try {
            return Double.valueOf(str);
        } catch (final NumberFormatException e) {
            return null;
        }
    }

    /**
     * Parse string to double, if string can't be parsed to double, then it will return given default value.
     *
     * @param str string to parse
     * @param def default value.
     *
     * @return parsed value or default value.
     */
    public static double asDouble(final String str, final double def) {
        try {
            return Double.parseDouble(str);
        } catch (final NumberFormatException e) {
            return def;
        }
    }
}

Related

  1. asDouble(String str)
  2. asDouble(String string)
  3. asDouble(String value)
  4. atof(String pString_)