为了账号安全,请及时绑定邮箱和手机立即绑定

如何舍入到最接近的0.5?

如何舍入到最接近的0.5?

慕丝7291255 2019-11-29 15:46:37
我必须显示收视率,为此,我需要增加如下值:如果数字是1.0,则应等于1;如果数字是1.1,则应等于1;如果数字是1.2,则应等于1;如果数字是1.3,则应等于1.5;如果数字是1.4,则应等于1.5如果数字为1.5,则应等于1.5;如果数字为1.6,则应等于1.5;如果数字为1.7,则应等于1.5;如果数字为1.8,则应等于2.0;如果数字是1.9,则应等于2.0如果数字为2.0应等于2.0如果数字为2.1应等于2.0依此类推...是否有一种简单的方法来计算所需的值?
查看完整描述

3 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

将您的评分乘以2,然后使用舍入Math.Round(rating, MidpointRounding.AwayFromZero),然后将该值除以2。


Math.Round(value * 2, MidpointRounding.AwayFromZero) / 2



查看完整回答
反对 回复 2019-11-29
?
蛊毒传说

TA贡献1895条经验 获得超3个赞

乘以2,取整,然后除以2


如果要最近的四分之一,请乘以4,再除以4,以此类推


查看完整回答
反对 回复 2019-11-29
?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

这是我编写的几种方法,它们总是可以向上或向下舍入为任何值。


public static Double RoundUpToNearest(Double passednumber, Double roundto)

{

    // 105.5 up to nearest 1 = 106

    // 105.5 up to nearest 10 = 110

    // 105.5 up to nearest 7 = 112

    // 105.5 up to nearest 100 = 200

    // 105.5 up to nearest 0.2 = 105.6

    // 105.5 up to nearest 0.3 = 105.6


    //if no rounto then just pass original number back

    if (roundto == 0)

    {

        return passednumber;

    }

    else

    {

        return Math.Ceiling(passednumber / roundto) * roundto;

    }

}


public static Double RoundDownToNearest(Double passednumber, Double roundto)

{

    // 105.5 down to nearest 1 = 105

    // 105.5 down to nearest 10 = 100

    // 105.5 down to nearest 7 = 105

    // 105.5 down to nearest 100 = 100

    // 105.5 down to nearest 0.2 = 105.4

    // 105.5 down to nearest 0.3 = 105.3


    //if no rounto then just pass original number back

    if (roundto == 0)

    {

        return passednumber;

    }

    else

    {

        return Math.Floor(passednumber / roundto) * roundto;

    }

}


查看完整回答
反对 回复 2019-11-29
  • 3 回答
  • 0 关注
  • 1387 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信