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