Click here to Skip to main content
15,907,874 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I've written the following code to divide the 2 numbers without rounding the answer:
C#
double a, b, c;
            a = double.Parse(textBox1.Text);
            b = double.Parse(textBox2.Text);

            c = a / b;

            label1.Text = c.ToString();

How do I make it round the number up?

What I have tried:

I've only tried the / operator. I'm new to C# therefore I don't know what else I can try.
Posted
Updated 16-Jun-18 15:08pm

To start with, don't use double.Parse to convert user input - if they make a single tiny mistake your app will crash. Use the Double.TryParse Method (String, Double) (System)[^] instead:
C#
double a;
if (!double.TryParse(textBox1.Text, out a))
   {
   ... report problem to user ...
   return;
   }
double b;
if (!double.TryParse(textBox2.Text, out b))
   {
   ... report problem to user ...
   return;
   }
Remember, users make typing mistakes all the time, just as we do! :laugh:

Then you can use either the Math.Round Method (Double) (System)[^] or Math.Round Method (Double, Int32) (System)[^] to round the result of your calculation.
C#
label1.Text = Math.Round(a / b).ToString();


BTW: Do yourself a favour, and stop using Visual Studio default names for everything - you may remember that "TextBox8" is the mobile number today, but when you have to modify it in three weeks time, will you then? Use descriptive names - "tbMobileNo" for example - and your code becomes easier to read, more self documenting, easier to maintain - and surprisingly quicker to code because Intellisense can get to to "tbMobile" in three keystrokes, where "TextBox8" takes thinking about and 8 keystrokes...
 
Share this answer
 
 
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