Java Float Number Create toFloat(String str)

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

Description

Convert a String to a float, returning 0.0f if the conversion fails.

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

 NumberUtils.toFloat(null)   = 0.0f NumberUtils.toFloat("")     = 0.0f NumberUtils.toFloat("1.5")  = 1.5f 

License

Open Source License

Parameter

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

Return

the float represented by the string, or 0.0f if conversion fails

Declaration

public static float toFloat(String str) 

Method Source Code

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

public class Main {
    /**/*  w ww . ja va2  s. co  m*/
     * <p>Convert a <code>String</code> to a <code>float</code>, returning
     * <code>0.0f</code> if the conversion fails.</p>
     *
     * <p>If the string <code>str</code> is <code>null</code>,
     * <code>0.0f</code> is returned.</p>
     *
     * <pre>
     *   NumberUtils.toFloat(null)   = 0.0f
     *   NumberUtils.toFloat("")     = 0.0f
     *   NumberUtils.toFloat("1.5")  = 1.5f
     * </pre>
     *
     * @param str the string to convert, may be <code>null</code>
     * @return the float represented by the string, or <code>0.0f</code>
     *  if conversion fails
     * @since 2.1
     */
    public static float toFloat(String str) {
        return toFloat(str, 0.0f);
    }

    /**
     * <p>Convert a <code>String</code> to a <code>float</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.toFloat(null, 1.1f)   = 1.0f
     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
     * </pre>
     *
     * @param str the string to convert, may be <code>null</code>
     * @param defaultValue the default symbol
     * @return the float represented by the string, or defaultValue
     *  if conversion fails
     * @since 2.1
     */
    public static float toFloat(String str, float defaultValue) {
        if (str == null)
            return defaultValue;
        try {
            return Float.parseFloat(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }
}

Related

  1. toFloat(String parameter)
  2. toFloat(String property, float f)
  3. toFloat(String s)
  4. toFloat(String s)
  5. toFloat(String s)
  6. toFloat(String str)
  7. toFloat(String str)
  8. toFloat(String str, float defaultValue)
  9. toFloat(String str, float defaultValue)