如何舍入到最接近的0.5?

Mur*_*dvi 94 c# math function

我必须显示评级,为此我需要增加如下:

如果数字是1.0则应该等于1
如果数字是1.1应该等于1
如果数字是1.2应该等于1
如果数字是1.3应该等于1.5
如果数字是1.4应该等于1.5 如果数字是1.4应该等于1.5
如果数字是1.5应该等于1.5
如果数字是1.6应该等于1.5
如果数字是1.7应该等于1.5
如果数字是1.8应该等于2.0
如果数字是1.8应该等于2.0 如果数字是1.9应该等于2.0
如果数字是2.0应该等于2.0
如果数字是2.1应该等于2.0
等等......

有没有一种简单的方法来计算所需的值?

Joh*_*sch 192

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

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

  • @neil:http://www.amazon.com/Atari-25649-Typing-Tutor-Dummies/dp/B0001IQN9I :) (11认同)
  • @Benjol,先划分然后舍入将使其舍入到最接近的因子2,而不是因子的一半.不正确. (7认同)
  • 我不需要打字傻瓜,我需要打字给聪明人 (4认同)
  • 先划分,然后再乘.这将消除溢出问题,并允许您舍入到任意数字. (4认同)
  • 不完美!整数溢出怎么样!您只能计算一半可能的整数. (3认同)
  • @Elazar - 如果你的排名可能高达1,073,741,823,我想不出一个用例,你会关心它是"十亿一个半"还是"十亿一个" - 如果这确实是一个问题那么排名方案本身存在一些缺陷:) (2认同)
  • @ElazarLeibovich 可以通过使用数字的分数来回避溢出问题。`varfraction = rating - Math.floor( rating)`,然后舍入这个分数或原始数字。 (2认同)

Nei*_*l N 61

乘以2,舍入,然后除以2

如果你想要最近的四分之一,乘以4,除以4,等等


NER*_*808 15

以下是我编写的几种方法,它们总是向上或向下舍入到任何值.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)