Giridhara krishnan
Giridhara krishnan

Reputation: 15

I'm Getting wrong calculations on discount percentage while using 10% and above. 1-9 % gets accurate answer

I'm Getting wrong calculations on discount percentage while using 10% and above. 1-9 % gets accurate answer

private void textBox6_TextChanged(object sender, EventArgs e)
{
    try
    {
        // if (string.IsNullOrEmpty(txtTaxPer.Text))
        if (string.IsNullOrEmpty(textBox6.Text))
        {
            //txtTaxAmt.Text = "";
            textBox7.Text = "";
            txtTotal.Text = "";
            return;
        }

        textBox7.Text = 
          Convert.ToDecimal(Convert.ToDecimal(txtTotal.Text) / 
          100 * 
          Convert.ToDecimal(textBox6.Text))
         .ToString("0.00");

        txtTotal.Text = 
          (Convert.ToDecimal(txtTotal.Text) - Convert.ToDecimal (textBox7.Text))
         .ToString("0.00");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Upvotes: 1

Views: 86

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Please, note that when you put, say 15 into textBox6.Text you have textBox6_TextChanged called twice, once for 1 and then for 15. Suppose we have txtTotal.Text == "1000.00". Then we start inputting 15: when we put 1 into textBox6.Text we have 1% from initial 1000.00:

 txtTotal.Text = 990.00    

then, when we put 5 and thus we have 15% from previously computed 990.00

 txtTotal.Text = 841.50

When the correct result (computing 15% from 1000.00) is

 txtTotal.Text = 850.00

I suggest having two textboxes, say txtTotal.Text and txtTotalWithDiscount.Text

private void textBox6_TextChanged(object sender, EventArgs e) {
  if (decimal.TryParse(txtTotal.Text, out decimal total) &&
      decimal.TryParse(textBox6.Text, out decimal percent)) {
    decimal discount = total / 100m * percent;

    textBox7.Text = (discount).ToString("0.00");
    txtTotalWithDiscount.Text = (total - discount).ToString("0.00");
  }
  else {
    //TODO: if txtTotal.Text or textBox6.Text is of invalid format
    // Or txtTotalWithDiscount.Text = txtTotal.Text;
    txtTotalWithDiscount.Text = "?";
  }
}

Upvotes: 2

Related Questions