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 ww .ja  v a2 s  .c om*/

    /**
     * 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;
    }
}