Jonatc87
Jonatc87

Reputation: 13

Round up if positive, round down if negative?

I'm trying to make it so the following figures are true:

etc
5 = -2
6 = -1
7 = -1
8 = 0
9 = +1
10 = +1
11 = +2

And so on.

What I'm using right now is :

function AbilityModifier( n)
{
    return Math.round( (n-8) /2);
}     

which returns correct positive figures, however it makes it so 7 = 0, 6 = -1, 5 = -1, etc. Which is wrong.

Is there a better formula that i could be using? Bare in mind i'm using NBOS character sheet designer.

Upvotes: 1

Views: 1470

Answers (2)

Keith.Abramo
Keith.Abramo

Reputation: 6955

function AbilityModifier(n)
{
    var x = n - 8;
    var round = x > 0 ? Math.ceil : Math.floor;
    return round(x / 2);
}    

Upvotes: 0

PawelP
PawelP

Reputation: 1180

function AbilityModifier(n)
{
    var x = n - 8;
    if (x > 0)
        return Math.ceil(x / 2);
    return Math.floor(x / 2);
}     

Upvotes: 4

Related Questions