Java - Write code to convert String To Float

Requirements

Write code to convert String To Float

Demo

//package com.book2s;

import java.math.BigDecimal;

public class Main {
    public static void main(String[] argv) {
        String sMt = "123123.123";
        System.out.println(convertStringToFloat(sMt));
    }/*from ww w .j a v a 2s .  co m*/

    public synchronized static float convertStringToFloat(String sMt) {
        float result = 0;
        try {
            BigDecimal bigDecimal = new BigDecimal(sMt);
            BigDecimal one = new BigDecimal("1");
            result = bigDecimal.divide(one, 2, BigDecimal.ROUND_HALF_UP)
                    .floatValue();
        } catch (Exception e) {

        }
        return result;
    }
}

Related Exercise