Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# midpointrounding down to zero

Tags:

c#

I know about MidpointRounding.AwayFromZero and MidpointRounding.ToEven, but I think I want something inbetween. It is for a promotions module, so discounted prices must round down if the value is .5.

For example, I would like:

£1.244 to round to £1.24
£1.245 to round to £1.24
£1.246 to round to £1.25

As I understand it, .AwayFromZero would round the middle value to £1.25 and .ToEven would round correctly to £1.24, but £1.335 would be rounded to £1.34, rather than £1.33 which is what I want.

Does anyone know how to accomplish this?

Thanks, Jon

like image 750
Jon Weir Avatar asked Oct 25 '25 02:10

Jon Weir


2 Answers

There is a lot of unspecified behavior. Let's keep it safe and do the rounding explicitly, ignoring negatives since this is about money:

    public static decimal Promotion(decimal value) {
        decimal unround = decimal.Floor(value * 100m);
        decimal fraction = value * 100m - unround;
        if (fraction <= 0.5m) return unround / 100m;
        else return (unround + 1m) / 100m;
    }
like image 60
Hans Passant Avatar answered Oct 26 '25 16:10

Hans Passant


Math.ceiling(x - 0.5)

Should do the trick.

like image 24
Ask About Monica Avatar answered Oct 26 '25 16:10

Ask About Monica