C#中点向下舍入到零 [英] C# midpointrounding down to zero

查看:59
本文介绍了C#中点向下舍入到零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道MidpointRounding.AwayFromZero和MidpointRounding.ToEven,但是我想我希望两者之间有一些联系.它是用于促销模块的,因此折扣值必须取整(如果值是.5).

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.

例如,我想要:


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

据我了解,.AwayFromZero将中间值四舍五入为1.25英镑,.ToEven将正确舍入为1.24英镑,但是1.335英镑将被四舍五入为1.34英镑,而不是我想要的1.33英镑.

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?

谢谢乔恩

推荐答案

有很多未指定的行为.让我们保持安全并明确地进行舍入,忽略负数,因为这与金钱有关:

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;
    }

这篇关于C#中点向下舍入到零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆