Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

universal parsing of strings into float

In the environment that my program is going to run, people use ',' and '.' as decimal separators randomly on PCs with ',' and '.' separators.

How would you implements such a floatparse(string) function?

I tried this one:

    try
    {
        d = float.Parse(s);
    }
    catch
    {
        try
        {
            d = float.Parse(s.Replace(".", ","));
        }
        catch
        {
            d = float.Parse(s.Replace(",", "."));
        }
    }

It doesn't work. And when I debugg it turns out that it parses it wrong the first time thinking that "." is a separator for thousands (like 100.000.000,0).

I'm noob at C#, so hopefully there is less overcomplicated solution then that :-)

NB: People a going to use both '.' and ',' in PCs with different separator settings.

like image 308
Vladimir Keleshev Avatar asked Jul 08 '10 15:07

Vladimir Keleshev


1 Answers

If you are sure nobody uses thousand-separators, you can Replace first:

string s = "1,23";  // or s = "1.23";

s = s.Replace(',', '.');
double d = double.Parse(s, CultureInfo.InvariantCulture);

The general pattern would be:

  • first try to sanitize and normalize. Like Replace(otherChar, myChar).
  • try to detect a format, maybe using RegEx, and use a targeted conversion. Like counting . and , to guess whether thousand separators are used.
  • try several formats in order, with TryParse. Do not use exceptions for this.
like image 63
Henk Holterman Avatar answered Sep 29 '22 18:09

Henk Holterman