Calculate percentage

Asked

Viewed 3,574 times

1

Largura * Complemento = Subtotal + Porcentagem = Total

subtotal.Text = (Convert.ToDouble(largura.Text) * Convert.ToDouble(complemento.Text)).ToString();
total.Text = (Convert.ToDouble(subtotal.Text) % Convert.ToDouble(PercaTextBox3.Text)).ToString();

Where I’m missing the percentage?

  • Largura * Complemento = Subtotal + Porcentagem = Total is a formula? This is not part of the code is not?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

5

The percentage symbol doesn’t calculate the percentage, you have to use the basic math to do that. Besides, I suggest learning to program in a more structured way. Learning in trial and error without knowing what you’re doing is harder, even if it doesn’t seem like it, spends more time, skips important things, and mostly teaches wrong causing tragedies.

There’s an extra error in your code that I’m gonna use to solve. Externally coming data conversion is not guaranteed and can break your application, you have to make sure you typed something that can be converted.

I did in Console because it is easier to demonstrate, but you adapt to Windows Forms. I even made one last conversion to string that will only make sense in Windows Forms.

There are meaningless conversions in the code. So reinforcement to understand what you are doing, in the current form is not learning to program. A phrase I always say:

If you don’t know everything your code does, including white space, you still don’t know how to program

using static System.Console;
    
public class Program {
    public static void Main() {
        var larguraText = "2.00";
        var alturaText = "1.00";
        var percText = "30";
        var total = 0.0;
        if (double.TryParse(larguraText, out var largura) && double.TryParse(alturaText, out var altura) && double.TryParse(percText, out var perc)) {
            total = largura * altura * (perc / 100);
        }
        var totalText = total.ToString(); //só para fins didáticos do exemplo
        WriteLine(totalText);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.