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#?
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);
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With