round(7) ---> 7
round(7.1) ---> 7
round(7.2) ---> nil
round(7.3) ---> nil
round(-5.2) ----> nil
round(-5.9) ----> -6
round(-5.1) ---> -5
round(-5.05) ----> -5
-- http://lua-users.org/wiki/SimpleRound
function round(num, numDecimalPlaces)
local mult = 10 ^ (numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end
function round_or_nil(num)
local diff = math.abs(math.fmod(num, 1))
if diff <= 0.1 or diff >= 0.9 then
return round(num)
end
return nil
end
print(round_or_nil(7))
print(round_or_nil(7.3))
print(round_or_nil(-5.2))
print(round_or_nil(-5.9))
print(round_or_nil(-5.1))
print(round_or_nil(-5.05))
Но на JS тоже годится
const roundOrNil = (n) => Math.abs(~~n - n) > 0.1 ? null : ~~n;
console.log(roundOrNil(7)); // 7
console.log(roundOrNil(7.3)); // null
console.log(roundOrNil(-5.2)); // null
console.log(roundOrNil(-5.9)); // null
console.log(roundOrNil(-5.1)); // -5
console.log(roundOrNil(-5.05)); // -5