Java Float Number Parse readFloatFromString(String inStr)

Here you can find the source of readFloatFromString(String inStr)

Description

Read float data from a string

License

Apache License

Parameter

Parameter Description
inStr a parameter

Exception

Parameter Description
Exception an exception

Declaration

protected static double readFloatFromString(String inStr) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParsePosition;

public class Main {
    /**//  w  w  w . jav  a  2s  .com
     * Read float data from a string
     * @param inStr
     * @return
     * @throws Exception 
     */
    protected static double readFloatFromString(String inStr) throws Exception {
        // make sure decimal sparator is '.' so it works in other countries
        // because of this can't use Double.parse
        DecimalFormat dformat = new DecimalFormat("#");
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setDecimalSeparator('.');
        dformat.setDecimalFormatSymbols(dfs);

        // trim white space and if there is a + at the start
        String trimStr = inStr.trim();
        if (trimStr.startsWith("+")) {
            trimStr = trimStr.substring(1);
        }

        // parse until we hit the end or invalid char
        ParsePosition pp = new ParsePosition(0);
        Number num = dformat.parse(trimStr, pp);
        if (null == num) {
            throw new Exception("Invalid Float In TLE");
        }

        return num.doubleValue();
    }
}

Related

  1. string2float(String arg, Locale loc)
  2. tryParseFloat(String floatValue)
  3. tryParseFloat(String value)
  4. tryParseFloat(String value)