Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conversion from string to double doesn't work well

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading