Click here to Skip to main content
15,908,673 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi frds,
I am working in windows form. I want to do percentage calculation. So if Percentage symbol is percent means it will do percentage operation otherwise it will show message box. How can i do this.

What I have tried:

this is for percentage calculation. But this want to proceed only percentage symbol is persent
decimal PercentageRate = Convert.ToDecimal(this.textBox1.Text);
int Rate = Convert.ToInt32(textBox2.Text.Replace("%", ""));
int Total = Convert.ToInt32(this.textBox2.Text.Replace("%", "")) * Convert.ToInt32(PercentageRate) / 100 + Convert.ToInt32(this.textBox1.Text); this.textBox3.Text = Total.ToString();
Updated 7-Mar-16 23:06pm
CHill60 8-Mar-16 4:48am    
Just to clarify what you are trying to do, what do you expect the users to type into each textbox ... please give an example
Michael_Davies 8-Mar-16 5:01am    
Why are you storing PercentageRate as a decimal if you do not need the fraction and then you convert it to Int32 which will discard the fraction and possibly round up the result depending on what the user types in textBox1.

Presuming textBox1 is the percentage you want, textBox2 is the gross value to find the percentage of. In you Total= line you may need to put parenthesis around the 100+ as divide has precedence over add so it executes as value divided by 100 then add textBox1 value, where you probably want :

PercentageValue = Total - (Total / (1.0 + PercentageRate / 100))

1 solution

It's pretty easy to check:
string s = "25%";
if (s.Contains("%"))
   // It's a percentage

string s = "25%";
s = s.Trim();
if (s.EndsWith("%"))
   // It's a percentage

But...That codes a bit...poor.
Don't use Convert.To - use Int.TryParse or Double.TryParse instead.
They give you a bool result which tells you "this wasn't a valid integer", or "this wasn't a valid double" and allows you to tell the user there is a problem instead of continuing with possibly the wrong values and the user doesn't know it.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900