Moz
Moz

Reputation: 39

Error in Decimal Calculation in c#

I am doing a windows form application in C# to calculate tax and add with total. after getting the total with a button click it should calculate the tax amount. if there are no decimal numbers it is working, but when it have to calculate decimal numbers giving an error as "the input string is not in correct format"

TotTax.Text = (Convert.ToInt32(textboxnettotal.Text) * (0.12)).ToString();
            textBox_GrnTot.Text = (Convert.ToInt32(textboxnettotal.Text) + Convert.ToInt32(TotTax.Text)).ToString();

and this my code

  1. while i am calculating total in c column of a data gridview decimal numbers it is not giving me the decimal value but i am getting Balanced full no answer in total textbox.

              int sum = 0;
            for (int i = 0; i < dataGridView1.Rows.Count; ++i)
            {
                sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[5].Value);
            }
                  textboxnettotal.Text = sum.ToString();
            RowCount++;
    

Upvotes: 1

Views: 2087

Answers (4)

Mahesh
Mahesh

Reputation: 1

double sum = 0;
    for (int i = 0; i < dataGridView1.Rows.Count; ++i)
    {
        sum += Convert.Todouble(dataGridView1.Rows[i].Cells[5].Value);
    }
          textboxnettotal.Text = sum.ToString();
    RowCount++;

Upvotes: 0

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26219

you can use Tryparse() method with InvariantCulture

decimal myvalue;
if (decimal.TryParse(dataGridView1.Rows[i].Cells[5].Value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out myvalue))
{
  sum += myvalue;
 }

Complete Code:

decimal myvalue;
decimal sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    if (decimal.TryParse(dataGridView1.Rows[i].Cells[5].Value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out myvalue))
    {
      sum += myvalue;
     }
}
  textboxnettotal.Text = sum.ToString();
  RowCount++;

Upvotes: 1

Anders Abel
Anders Abel

Reputation: 69300

int that you are converting to with Convert.ToInt32 doesn't support decimals. Use the Decimal data type instead. It allows decimals and it doesn't have some of the odd rounding behaviour of float or double.

Upvotes: 1

King King
King King

Reputation: 63387

Use Convert.ToDecimal instead of Convert.ToInt32, to be sure your sum is declared as decimal.

Upvotes: 3

Related Questions