Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round up a number

Tags:

c#

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#?

like image 296
ANP Avatar asked Aug 02 '10 12:08

ANP


4 Answers

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);
like image 89
Quartermeister Avatar answered Sep 22 '22 07:09

Quartermeister


 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.

like image 20
Venkat Avatar answered Sep 23 '22 07:09

Venkat


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.

like image 21
Anindya Chatterjee Avatar answered Sep 19 '22 07:09

Anindya Chatterjee


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;
like image 38
juanma Avatar answered Sep 23 '22 07:09

juanma