Home > Software engineering >  Conversion from string to double doesn't work well
Conversion from string to double doesn't work well

Time:07-01

I'm trying to carry out a conversion from a string to a double. I have values like "000.2" or "000.7". I'm trying to use them for a chart. But when I use y = Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);

and the actual value of the dataGridView is "000.7" the output will be 7????

I do not understand this.

        int rows = dataGridView1.RowCount;
        int x;
        double y;

        for (int i = 0; i < rows; i  )
        {
            x = Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
            y = Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
            this.chartHorizontal.Series["Horizontal"].Points.AddXY(x, y);
        }

Maybe someone knows what goes wrong here?

Suggested thread doesn't show me what goes wrong.

CodePudding user response:

Convert.ToDouble calls Double.Parse(string s, IFormatProvider provider) internally with CultureInfo.CurrentCulture as the provider argument (see here).

It's likely that CultureInfo.CurrentCulture is causing "000.7" to be interpreted as "7" - for example, passing new CultureInfo("de") as the second parameter to Convert.ToDouble produces the same result for me that you're seeing.

To get around this, try passing CultureInfo.InvariantCulture explicitly:

y = Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value, CultureInfo.InvariantCulture);

From the documentation:

Unlike culture-sensitive data, which is subject to change by user customization or by updates to the .NET Framework or the operating system, invariant culture data is stable over time and across installed cultures and cannot be customized by users. This makes the invariant culture particularly useful for operations that require culture-independent results, such as formatting and parsing operations that persist formatted data, or sorting and ordering operations that require that data be displayed in a fixed order regardless of culture.

  • Related