ANP
ANP

Reputation: 15607

How to round up a number

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

Answers (4)

Anindya Chatterjee
Anindya Chatterjee

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

juanma
juanma

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

Venkat
Venkat

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

Quartermeister
Quartermeister

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

Related Questions