Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I round up or down in C#?

Tags:

c#

math

I have tried using Math.Round and MidpointRounding. This does not appear to do what I need.

Example:

52.34567 rounded to 2 decimals UP   = 52.35
 1.183   rounded to 2 decimals DOWN =  1.18

Do I need to write a custom function?

Sometimes I need a number like 23.567 to round DOWN to 23.56. In this scenario...

Math.Round(dec, 2, MidpointRounding.AwayFromZero) gives 23.57
Math.Round(dec, 2, MidpointRounding.ToEven) gives 23.57

Decimals up to 9 decimal places could come out and need to be rounded to 1, 2, 3 or even 4 decimal places.

like image 260
B-Rad Avatar asked Sep 05 '25 03:09

B-Rad


2 Answers

Try using decimal.Round():

decimal.Round(x, 2)

Where x is your value and 2 is the number of decimals you wish to keep.

You can also specify whether .5 rounds up or down by passing third parameter:

decimal.Round(x, 2, MidpointRounding.AwayFromZero);

EDIT:

In light of the new requirement (i.e. that numbers are sometimes rounded down despite being greater than "halfway" to the next interval), you can try:

var pow = Math.Pow(10, numDigits);
var truncated = Math.Truncate(x*pow) / pow;

Truncate() lops off the non-integer portion of the decimal. Note that numDigits above should be how many digits you want to KEEP, not the total number of decimals, etc.

Finally, if you want to force a round up (truncation really is a forced round-down), you would just add 1 to the result of the Truncate() call before dividing again.

like image 192
atkretsch Avatar answered Sep 09 '25 01:09

atkretsch


Try using Math.Ceiling (up) or Math.Floor (down). e.g Math.Floor(1.8) == 1.

like image 31
pascalhein Avatar answered Sep 09 '25 00:09

pascalhein