Click here to Skip to main content
15,886,065 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a web form that does calculations by textbox text change. I have a code that divides two numbers and shows the answer in another textbox. The answer is then rounded and shown in the textbox. The answer shown is not rounded right. Here is what I have:

Textbox1 = 923

b = 120

Textbox3 = answer

Here is the calculation:
C#
int a = Convert.ToInt32(Textbox1.Text);
int b = 120;
Textbox3.text = Convert.ToString(a / b);

Textbox3 answer is 7.691666666666667
Here is my rounding code:
C#
Textbox3.Text = Math.Round(Convert.ToDouble(TextBoxNCCDR.Text), 2).ToString();

When the answer is rounded the new answer is 7. Why is it not 8? How can I get the rounding to round to the nearest whole number?
Posted
Updated 18-Nov-14 6:42am
v4
Comments
PIEBALDconsult 18-Nov-14 12:37pm    
Unclear.
7.691.666666666667 has an extra decimal point.
923 / 168 is 5
What is TextBoxNCCDR.Text ?

Please use Improve question to clarify what you are trying to do.

1 solution

Because it's integer arithmetic - and it doesn't know anything about fractional parts!
Change all your int values to double and it'lkl do what you expected:
C#
double a = Convert.ToDouble(Textbox1.Text);
double b = 168;
Textbox3.text = (a / b).ToString();


BTW: The standard way to do any type to a string is to use the ToString method for the class rather than Convert.ToString - every type implements it, and your classes can override it to produce a meaningful message.

And rounding up is easy: Math.Ceiling will do it:
C#
Console.WriteLine(Math.Ceiling(7.6916666666));
Will give you 8
 
Share this answer
 
v2
Comments
Computer Wiz99 18-Nov-14 12:43pm    
OriginalGriff, that worked. Thanks. Do I have to change all of the int to Double in my code or just for the rounding?
OriginalGriff 18-Nov-14 13:33pm    
Depends on what you are trying to do.
Of you want to hold, work with, or process any values which have fractional part then you can't use an integer value - as they will automatically discard it and truncate the value:
Double - 12.3
To integer - 12
To double - 12.0

So if you want fractional values at any point, it's best to keep to double values throughout and only use ints when you really need an integer value.

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