Java String to Float asFloat(final String str, final float def)

Here you can find the source of asFloat(final String str, final float def)

Description

Parse string to float, if string can't be parsed to float, 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 float asFloat(final String str, final float def) 

Method Source Code

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

public class Main {
    /**/*from   w  ww  . j ava2 s  .c  o m*/
     * Parse string to float, if string can't be parsed to float, then it will return null.
     *
     * @param str string to parse
     *
     * @return parsed value or null.
     */
    public static Float asFloat(final String str) {
        try {
            return Float.valueOf(str);
        } catch (final NumberFormatException e) {
            return null;
        }
    }

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

Related

  1. asFloat(String string)
  2. asFloat(String v)
  3. asFloat(String value)
  4. atof(final String str, final float def)