Display data from a DataGridView column in float

3

I'm developing an application in Windows C # which takes the order inside a datagridview and when you press the "calculate total" button you have to add the "Cost" column. The problem is that I do not respect the decimals since it shows the whole number as an integer as the following image shows:

Instead of showing me 65.5, it shows me 655.

This is the code I use when I press the button:

private void button6_Click(object sender, EventArgs e)
        {
            for (int numColumna = 0; numColumna < dataGridView1.Columns.Count; numColumna++)
            {
                float sumTotal =0F;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                { 
                    sumTotal += Convert.ToSingle(row.Cells[1].Value);  
                }
                textBox1.Text = sumTotal.ToString();
            }
        }

Try to put it in the following way:

 private void button6_Click(object sender, EventArgs e)
        {
            for (int numColumna = 0; numColumna < dataGridView1.Columns.Count; numColumna++)
            {
               var sumTotal ="";

                foreach (DataGridViewRow row in dataGridView1.Rows)
                {

                    sumTotal +=Convert.ToString(row.Cells[1].Value);
                    Convert.ToSingle(sumTotal);
                    MessageBox.Show(sumTotal);
                    }
                MessageBox.Show(sumTotal);
                textBox1.Text = sumTotal.ToString();
            }
        }

And what happens is that at the moment of doing the sum now it appears to me in the following way:

    
asked by Ezequie Lopez 12.09.2018 в 20:49
source

2 answers

2

Friends, thanks for the help, the error was in the query, I did not know that the function RTRIM and LTRIM removed the "," and ".":

SqlDataAdapter agregar = new SqlDataAdapter("Select  (RTRIM(LTRIM(Nombre))) as Nombre,(RTRIM(LTRIM(Costo))) as Costo from entradas where Nombre = 'Dedos de queso' and costo= '79.50'", cadena);

Modified:

 SqlDataAdapter agregar = new SqlDataAdapter("Select  (RTRIM(LTRIM(Nombre))) as Nombre,Costo from entradas where Nombre = 'Dedos de queso' and costo= '79.50'", cadena);
    
answered by 13.09.2018 / 00:11
source
2

You can use the standard numeric format specifiers in the ToString() method. You can check them in this link .

In your particular case, to get the exact number in string you can use the "R" specifier, for example:

float sumTotal = 65.5f;
string numberString = sumTotal.ToString("R");
    
answered by 12.09.2018 в 21:22