开发者

Can Math.Round in C# be used for whole integer values?

I have integer 363 for example.

Any method to make it 360开发者_开发问答 or 365?


This is a hack, but it works:

var rounded = Math.Round(363 / 5f) * 5;


There's nothing built-in, you're just going to have to code the logic yourself. Here's one such method. (Going down is clearer, but going up is manageable.)

int number = 363;
int roundedDown = number - number % 5;
int roundedUp = number + (number % 5 > 0 ? (5 - number % 5) : 0);

Edit for negative numbers, the logic almost gets reversed.

static int RoundUpToFive(int number)
{
    if (number >= 0)
        return number + (number % 5 > 0 ? (5 - number % 5) : 0);
    else
        return number - (number % 5);
}

static int RoundDownToFive(int number)
{
    if (number >= 0)
        return number - number % 5;
    else
        return number + (number % 5 < 0 ? (-5 - number % 5) : 0);
}


Here's what I usually do, which is a combination of the two ideas:

static int RoundDown(int x, int n) {
    return x / n * n;
}

static int Round(int x, int n) {
    return (x + n / 2) / n * n;
}

static int RoundUp(int x, int n) {
    return (x + n - 1) / n * n;
}

(That assumes positive numbers; Extending it to negatives is straight-forward.)

[edit]

According to LLVM, the Round function can also be written like this:

int Round(int x, int n) {
    int z = (x + n / 2);
    return z - (z % n);
}

Which you may find more elegant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜