Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round up value C# to the nearest integer?

Tags:

c#

math

rounding

I want to round up double to int.

Eg,

double a=0.4, b=0.5; 

I want to change them both to integer.

so that

int aa=0, bb=1; 

aa is from a and bb is from b.

Any formula to do that?

like image 207
william Avatar asked Oct 13 '10 03:10

william


People also ask

How do you round up in C?

In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).

Does C programming round up or down?

Integer division truncates in C, yes. (i.e. it's round towards zero, not round down.) round toward 0 meaning . 5 or greater => round up 0 to .

How do you round down in C?

In the C Programming Language, the floor function returns the largest integer that is smaller than or equal to x (ie: rounds downs the nearest integer).

How do you round up in C++?

round() in C++ round is used to round off the given digit which can be in float or double. It returns the nearest integral value to provided parameter in round function, with halfway cases rounded away from zero. Instead of round(), std::round() can also be used .


2 Answers

Use Math.Ceiling to round up

Math.Ceiling(0.5); // 1 

Use Math.Round to just round

Math.Round(0.5, MidpointRounding.AwayFromZero); // 1 

And Math.Floor to round down

Math.Floor(0.5); // 0 
like image 146
BrunoLM Avatar answered Sep 19 '22 12:09

BrunoLM


Check out Math.Round. You can then cast the result to an int.

like image 34
Larsenal Avatar answered Sep 18 '22 12:09

Larsenal