Java - Write code to Convert a string to a float value.

Requirements

Write code to Convert a string to a float value.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String dataString = "12312312.231233fF";
        float defaultValue = 42.45678f;
        System.out.println(stringToFloatDef(dataString, defaultValue));
    }/*from   w w  w  . j  a v a  2 s  .  c  o  m*/

    /**
     * Converts a string to a float value. If the conversion fails, the default value is returned.
     */
    public static float stringToFloatDef(String dataString,
            float defaultValue) {
        try {
            return Float.parseFloat(dataString);
        } catch (Exception e) {
        }
        return defaultValue;
    }
}

Related Exercise