Java Double Number Create toDouble(String str)

Here you can find the source of toDouble(String str)

Description

Convert a String to a double, returning 0.0d if the conversion fails.

If the string str is null, 0.0d is returned.

 NumberUtils.toDouble(null)   = 0.0d NumberUtils.toDouble("")     = 0.0d NumberUtils.toDouble("1.5")  = 1.5d 

License

Open Source License

Parameter

Parameter Description
str the string to convert, may be <code>null</code>

Return

the double represented by the string, or 0.0d if conversion fails

Declaration

public static double toDouble(String str) 

Method Source Code

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

public class Main {
    /**/*  ww  w.j av a2  s.  c o  m*/
     * <p>Convert a <code>String</code> to a <code>double</code>, returning
     * <code>0.0d</code> if the conversion fails.</p>
     *
     * <p>If the string <code>str</code> is <code>null</code>,
     * <code>0.0d</code> is returned.</p>
     *
     * <pre>
     *   NumberUtils.toDouble(null)   = 0.0d
     *   NumberUtils.toDouble("")     = 0.0d
     *   NumberUtils.toDouble("1.5")  = 1.5d
     * </pre>
     *
     * @param str the string to convert, may be <code>null</code>
     * @return the double represented by the string, or <code>0.0d</code>
     *  if conversion fails
     * @since 2.1
     */
    public static double toDouble(String str) {
        return toDouble(str, 0.0d);
    }

    /**
     * <p>Convert a <code>String</code> to a <code>double</code>, returning a
     * default symbol if the conversion fails.</p>
     *
     * <p>If the string <code>str</code> is <code>null</code>, the default
     * symbol is returned.</p>
     *
     * <pre>
     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
     * </pre>
     *
     * @param str the string to convert, may be <code>null</code>
     * @param defaultValue the default symbol
     * @return the double represented by the string, or defaultValue
     *  if conversion fails
     * @since 2.1
     */
    public static double toDouble(String str, double defaultValue) {
        if (str == null)
            return defaultValue;
        try {
            return Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }
}

Related

  1. toDouble(String s)
  2. toDouble(String s)
  3. toDouble(String str)
  4. toDouble(String str)
  5. toDouble(String str)
  6. toDouble(String str)
  7. toDouble(String str)
  8. toDouble(String str, double defaultValue)
  9. toDouble(String string)