lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> I want a function like math.round.
> 
> > math.round(100000*1.005)
> 100500

To get IEEE compliant rounding you can force it to occur by scaling the number.  The function you then want is as follows (for standard 64 bit Lua, for 32 bit different constants are needed):

```lua
function rint(x)
    if x < 0 then
        return ((x - 0x1p+52) + 0x1p+52) | 0
    end
    return ((x + 0x1p+52) - 0x1p+52) | 0
end
```

If your argument is not expressible as an integer then this will cause an error so you should wrap it in `pcall` if the argument could be larger than `math.maxinteger` (or smaller than `math.mininteger`).

The difference between this function and `math.floor(x+0.5)` is that it correctly rounds midway results to even, which is required for numerical stability of functions (if somewhat surprising to people used to half round up, or half round away).  Essentially by IEEE 0.5 should round to 0, and 1.5 to 2.

Regards,

Duane.