简体   繁体   中英

Convert String with Dot or Comma to Float Number

I always like input in my function to get numbers that range from 0.1 to 999.9 (the decimal part is always separated by '.', if there is no decimal then there is no '.' for example 9 or 7 .

How do I convert this String to float value regardless of localization (some countries use ',' to separate decimal part of number. I always get it with the '.')? Does this depend on local computer settings?

The Float.parseFloat() method is not locale-dependent. It expects a dot as decimal separator. If the decimal separator in your input is always dot, you can use this safely.

The NumberFormat class provides locale-aware parse and format should you need to adapt for different locales.

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
DecimalFormat format = new DecimalFormat("0.#");
format.setDecimalFormatSymbols(symbols);
float f = format.parse(str).floatValue();
valueStr = valueStr.replace(',', '.');
return new Float(valueStr);

Done

What about this:

Float floatFromStringOrZero(String s){
    Float val = Float.valueOf(0);
    try{
        val = Float.valueOf(s);
    } catch(NumberFormatException ex){
        DecimalFormat df = new DecimalFormat();
        Number n = null;
        try{
            n = df.parse(s);
        } catch(ParseException ex2){
        }
        if(n != null)
            val = n.floatValue();
    }
    return val;
}

See java.text.NumberFormat and DecimalFormat :

 NumberFormat nf = new DecimalFormat ("990.0");
 double d = nf.parse (text);

I hope this piece of code may help you.

public static Float getDigit(String quote){
        char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
        String regex = "[^0-9" + decimalSeparator + "]";
        String valueOnlyDigit = quote.replaceAll(regex, "");

        if (String.valueOf(decimalSeparator).equals(",")) {
            valueOnlyDigit = valueOnlyDigit.replace(",", ".");
            //Log.i("debinf purcadap", "substituted comma by dot");
        }

        try {
            return Float.parseFloat(valueOnlyDigit);
        } catch (ArithmeticException | NumberFormatException e) {
            //Log.i("debinf purcadap", "Error in getMoneyAsDecimal", e);
            return null;
        }
    }

Maybe it's a little bit late (10years old Post), but the actual answers are way to "complicate" and maybe someone else is seeking for this.

You can use the Placeholder %s-String for nearly anything.

Say you have:

float x = 3.15f, y = 1.2345f;

System.out.printf("%.4s and %.5s", x, y);

Displays: 3.15 and 1.234

%s is always english formatting regardless of localization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM