Reputation: 15607
I have variable like float num = (x/y); I need to round up the result whenever num gives result like 34.443. So how to do this in c#?
Upvotes: 10
Views: 7668
Reputation: 5964
Use Math.Ceiling
if you want the integer greater than the answer, or Math.Floor
if you want an integer less than the answer.
Example
Math.Ceiling(3.46) = 4;
Math.Floor(3.46) = 3;
Use whichever is required for your case.
Upvotes: 2
Reputation: 9
if you need 2 decimal, yo can use something like:
float roundedvalue = (float)Math.Ceiling(x*100/y) /100;
float roundedvalue = (float)Math.Floor(x*100/y) /100;
Upvotes: 1
Reputation: 878
float num = (x/y);
float roundedValue = (float)Math.Round(num, 2);
If we use Math.Round function we can specify no of places to round.
Upvotes: 5
Reputation: 59139
Use Math.Ceiling:
Returns the smallest integer greater than or equal to the specified number
Note that this works on doubles, so if you want a float (or an integer) you will need to cast.
float num = (float)Math.Ceiling(x/y);
Upvotes: 25