Convert String with Dot or Comma to Float Number
Asked Answered
L

8

35

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?

Luce answered 8/3, 2011 at 13:19 Comment(0)
F
32

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.

Fidele answered 8/3, 2011 at 13:30 Comment(1)
beware of pitfalls with NumberFormat - it is not threadsafe and it does not validate its input, for example "0x123" -> 0, "3.14" -> 3.14 but "3,14" -> 314 (assuming US local). See my question/answer here: #77996284Stoneware
S
29
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
DecimalFormat format = new DecimalFormat("0.#");
format.setDecimalFormatSymbols(symbols);
float f = format.parse(str).floatValue();
Sinistrodextral answered 8/3, 2011 at 14:14 Comment(5)
Alternatively, new DecimalFormat("0.#", DecimalFormatSymbols.getInstance(Locale.ENGLISH));Lewse
Yes, but you're relying on the system settingsSinistrodextral
How so? Won't hard coding the English locale use dot separator regardless of system settings?Lewse
No: the user can change the format of numbers for the english language.Sinistrodextral
This is very very slow if you need to make 1000+ conversions. Use the solution below with the "replace" for much better speed.Kevinkevina
I
26
valueStr = valueStr.replace(',', '.');
return new Float(valueStr);

Done

Insessorial answered 7/12, 2012 at 6:53 Comment(6)
This is really a bad solution.. for a great amount of values, this could be a bottleneck. Really bad performance!Design
Why? All it effectively is, is a series of primitive character comparisons, then the creation of a new String, then a parseFloat. It's less expensive to create a String then a DecimalFormat, DecimalFormatSymbols or any of this malarkey. Gimme my point back =)Insessorial
The replace needs to parse all the string unless he find the comma, and is not safe in case of change of locale. There are better way to have a mechanism working for both cases. Parsing a string in this way can be a bottleneck if you're using the function for a lot of times per secondDesign
Naturally it's an ad-hoc solution; it's only safe when you're sure that the String double values you're getting will definitely always be using commas or dots. Otherwise you can use the replaceAll(String, String) with a regex to match multiple types of possible seperators/delimiters at once; although it would be slower for sure. Anyway, I don't know how the internals of the DecimalFormat work; but I don't see how it will be faster. Even if it is, then this is still a perfectly reasonable solution in MOST casesInsessorial
This is the best solution related to speed, the others are very very slow if you need to make 1000+ conversions.Kevinkevina
This only works when the number does not use thousands seperators - it would not correctly parse "1.000,0" as one thousand.Stoneware
J
6

See java.text.NumberFormat and DecimalFormat:

 NumberFormat nf = new DecimalFormat ("990.0");
 double d = nf.parse (text);
Jook answered 8/3, 2011 at 13:29 Comment(0)
B
6

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;
}
Barthold answered 12/1, 2014 at 11:33 Comment(0)
G
1

You can use the placeholder %s-String for any primitive type.

float x = 3.15f, y = 1.2345f;

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

Output: 3.15 and 1.234

%s is always english formatting regardless of localization.

If you want a specif local formatting, you could also do:

import java.util.Locale;

float x = 3.15f, y = 1.2345f;

System.out.printf(Locale.GERMAN, "%.2f and %.4f", x, y);

Output: 3,15 and 1,2345

Girovard answered 2/1, 2022 at 20:15 Comment(0)
R
0

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;
        }
    }
Ridgway answered 6/3, 2019 at 0:37 Comment(0)
J
0

To convert the string to float regardless of localization you can always replace the comma "," with the dot "." using the str.replace() method, as following:

// Set value as string first
String s = "9,9";
// Replacing , with .
s = s.replace(",", ".");
// Parsing the value
float x = Float.parseFloat(s);
Jeannajeanne answered 8/8, 2023 at 19:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.