Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to calculate percentage, and I have done it but unable to get value in which format I want.
suppose I am calculating following
(579803.4 * 14%)=81,172.476
but I want to 81,172.48 after calculation. what should I do?


Thanks In advance

What I have tried:

textBox1.Text = (((float.Parse(textBox2.Text)) * (float.Parse(textBox3.Text)) / 100)).ToString();
Posted
Updated 29-Jun-21 7:52am
Comments
Richard Deeming 28-Apr-16 10:08am    
What if the user enters something that's not a valid number? Your code will fail with an exception. You should use the TryParse[^] method instead; that way, you can display a suitable error message if one of the values isn't a number.

Try
C#
textBox1.Text = (((float.Parse(textBox2.Text)) * (float.Parse(textBox3.Text)) / 100)).ToString("F2");
 
Share this answer
 
First off, don't use Parse on user input: use TryParse instead:
C#
double d1, d2;
if (!double.TryParse(textBox2.Text, out d1))
    {
    MessageBox.Show(string.Format("{0} is not a number", textBox2.Text));
    return;
    }
if (!double.TryParse(textBox3.Text, out d2))
    {
    MessageBox.Show(string.Format("{0} is not a number", textBox3.Text));
    return;
    }
textBox1.Text = (d1 * d2 / 100).ToString("#.00");
That way, your app won't crash if your user misskeys...
 
Share this answer
 
Use

ToString("0.00"); //2dp Number

Or

Math.Round(yourAmount,2)

for 2 decimal.
 
Share this answer
 
v2

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