Correct and reliable rounding function for SilverBullet?

I ran into tremendous troubles with my attempts to write Lua math.round() function for SilverBullet. I finally ended with [1]:

```space-lua
math = math or {}

local ROUNDING_BOUNDARY = 2^52

function math.round(num)
  if math.abs(num) > ROUNDING_BOUNDARY then
    return num
  end

  return num < 0
     and num - ROUNDING_BOUNDARY + ROUNDING_BOUNDARY
      or num + ROUNDING_BOUNDARY - ROUNDING_BOUNDARY
end
```

This (a tricky one) function is the only one I could find and try that gives me correct (expected) results for the following function that tries to improve UX for visual representation (numeric, bar, etc.) of some progress [2]:

```space-lua
calc = calc or {}

-- improve UX
function calc.progress(progress, total)
  total = total or 100 -- assume %

  return math.round(99 * progress / total + 0.5)
end
```

Because I cannot know (from inside of the SilverBullet’s Lua) how is the FPU configured and all the other stuff (even precision), would it make sense to implement math.round() in TypeScript inside the SilverBullet’s core to avoid all sorts of effects and ambiguities that can arise?

FP math seems extremely sensitive to so many aspects and there are so many things involved that can get wrong that I really doubt (despite the fact the above math.round() works as expected and both the functions pass the tests provided by their authors clearly and play well together) that it is good or healthy approach to write such who-knows-what-dependens-on stuff like the rounding function in the interpreted Lua (be it classical Lua on my system I will try to find or write a C module for this, TBH).

What do you think? (Also pinging @zef because it’s possible that the issue cannot be solved elswhere than in the SilverBullet’s core.)


Sidenote: From my PoW we should have all variants of rounding modes because sometimes you need this and sometimes it appears you need that. [3] Most languages provides functions like round() or round_tie_even() in the standard libraries.


  • [1] Stack Overflow discussion about rounding in Lua (the whole thread is worth reading, by the way, because it shows how hard is this problem)
  • [2] Great and truthful article about rounding percentages and UX
  • [3] Wikipedia on rounding :wink: