[Solved] Rounding function in JASS

Status
Not open for further replies.
Since R2I truncates you can do:

Floor = I2R(R2I(num))
Ceiling = I2R(R2I(num + 1.0))
Round = I2R(R2I(num + 0.5))

Take off the outer I2Rs and you'll get integers out of it. There are also min/max BJs in Blizzard.j I think they're called rminb() and rmaxbj()?

That is not really true.
Ceiling fails when it is a whole number. (2.0 will turn out as 3)
Floor and Ceiling fail on negative numbers. (Floor(-2.5) should be -3 but will result -2 and Ceiling(-2.5) should return -2 but results -1)
And they should return integers... should they?
 
Okay so if the number is negative or .00000000000 exactly then
That is not really true.
Ceiling fails when it is a whole number. (2.0 will turn out as 3)
Floor and Ceiling fail on negative numbers. (Floor(-2.5) should be -3 but will result -2 and Ceiling(-2.5) should return -2 but results -1)
And they should return integers... should they?
Having r == X.00000000 exactly seems incredibly rare, given floating point precision. Return type matters to the user, so they should set it; IDK if they want reals or ints.
JASS:
function floor takes real r returns real
    local real add = 0.00
    if (r < 0.00) or (I2R(R2I(r)) == r) then
        set add = -1.00
    endif

    return I2R(R2I(r+add))
endfunction

function ceiling takes real r returns real
    local real add = 0.00
    if (r < 0.00) or (I2R(R2I(r)) == r) then
        set add = -1.00
    endif

    return I2R(R2I(r+1.00+add))
endfunction

function round takes real r returns real
    local real add = 0.00
    if (r < 0.00) or (I2R(R2I(r)) == r) then
        set add = -1.00
    endif

    return I2R(R2I(r+0.50+add))
endfunction
 
Hmm, it seems that normal languages also use floats... I wonder why.

JASS:
struct Math
        // Rounding
        static method floor takes real r returns real
            if r < 0 then
                return -I2R(R2I(-r))
            endif
            return I2R(R2I(r))
        endmethod
       
        static method ceil takes real r returns real
            if floor(r) == r then
                return r
            elseif r < 0 then
                return -(I2R(R2I(-r)) + 1.0)
            endif
            return I2R(R2I(r)) + 1.0
        endmethod
       
        static method round takes real r returns real
            if r > 0 then
                return I2R(R2I(r + 0.5))
            endif
            return I2R(R2I(r - 0.5))
        endmethod
endstruct
 
Status
Not open for further replies.
Back
Top