Java - Write code to parse a string in 123,123.12 format to Float

Requirements

Write code to parse a string in 123,123.12 format to Float

Demo

//package com.book2s;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;

public class Main {
    public static void main(String[] argv) {
        String floatString = "123,123.12";
        System.out.println(toFloat(floatString));
    }/*from   w  w  w  .j  ava2s .  co m*/

    public static float toFloat(String floatString) {
        float result = 0;

        DecimalFormatSymbols sym = new DecimalFormatSymbols();
        sym.setDecimalSeparator(',');
        DecimalFormat form = new DecimalFormat("");
        form.setDecimalFormatSymbols(sym);
        Number num;
        try {
            num = form.parse(floatString);
        } catch (ParseException e) { //'if string doesn't parse as string, just return 0
            return result;
        }
        result = num.floatValue();

        return result;
    }
}

Related Exercise