Here you can find the source of toDouble(String str)
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
Parameter | Description |
---|---|
str | the string to convert, may be <code>null</code> |
0.0d
if conversion fails
public static double toDouble(String str)
//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; } } }