william
william

Reputation: 7674

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?

Upvotes: 4

Views: 1258

Answers (3)

me22
me22

Reputation: 641

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.

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126932

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

Upvotes: 5

cdhowie
cdhowie

Reputation: 169143

This is a hack, but it works:

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

Upvotes: 8

Related Questions