Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua - How to get decimals to round down on the half

Tags:

rounding

lua

I'm using this function to round currently:

function round(val, decimal)
  if (decimal) then
    return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
  else
    return math.floor(val+0.5)
  end
end

That function works perfectly except that when a number lands on .5 like 5.5 or 1000.5 or 7.5 I need it to round down instead of up. What changes would I have to make to the function to make that happen?

like image 943
Mark Kramer Avatar asked Dec 21 '25 10:12

Mark Kramer


1 Answers

function round(val, decimal)
  local exp = decimal and 10^decimal or 1
  return math.ceil(val * exp - 0.5) / exp
end
like image 104
Egor Skriptunoff Avatar answered Dec 24 '25 10:12

Egor Skriptunoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!