0

How can I read float values with comma like 123,45?

I have to read third party excel files that come formatted like 123,45 and I can not / am not allowed to reformat them to 123.45.

I am now using this method:

    string GetCell(int row, int col)
    {
        if (Sheet != null)
        {
            try
            {
                string cellContent = Sheet[row][col].ToString(); // careful "ToString()" syntax!
                //Print("Excel.Get({0},{1}): {2}", row, col, cellContent);
                return cellContent;
            }
            catch (Exception e)
            {
                Print("Excel.Get("+row+","+col+") error: "+ e.Message);
                return null;
            }
        }
        else
        {
            Print("Excel.Get("+ row + ","+ col+") error: sheet is null");
            return null;
        }
    }

but the string is returned as 12345.

Thanks in advance!

  • 2
    You can read (parse) "123,45" as `12345` or `123.45`... which way you like? (please [edit] post to clarify) – Alexei Levenkov Jan 21 '20 at 05:51
  • read them by setting a culture / locale that use commas as decimal separator, like French language/culture for instance. – Pac0 Jan 21 '20 at 06:30
  • I still don't get which result you want... Anyway as @Pac0 said pick a culture and [set it for current thread or whole process](https://stackoverflow.com/questions/468791/is-there-a-way-of-setting-culture-for-a-whole-application-all-current-threads-a). Pick culture that either treats `,` as decimal separator (to get `123.45`) or group separator (to get `12345`) – Alexei Levenkov Jan 21 '20 at 06:34
  • yes, set the Culture for current thread, or use float.Parse with the culture argument. – Pac0 Jan 21 '20 at 06:35

1 Answers1

3

You could try to specify a culture

    string valueRead = "123,45";
    CultureInfo frenchCultureInfo = new CultureInfo("fr-FR");
    float valueParsed = float.Parse(valueRead, frenchCultureInfo);

EDIT : as per your comment, you can specify the culture using the Excel interop. Other choices include, read values as string and use float.Parse, or change the culture of the current thread.

I used French because comma is a decimal separator in this language, but of course any other language for which it's the case should fit.

Pac0
  • 21,465
  • 8
  • 65
  • 74
  • Thanks! it worked putting `CultureInfo frenchCultureInfo = new CultureInfo("fr-FR")` at the beginning of my `Excel` class –  Jan 21 '20 at 07:21