Answer the question
In order to leave comments, you need to log in
What is the most elegant way to make a function that rounds a number only if it is closer than 0.1 to the integer, otherwise nil?
Generally needed for Lua.
But it is also suitable for JS, just then only Math.floor() can be used from functions, and instead of nil, you can return any non-number (undefined, null, NaN, false, "false", etc.).
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
Answer the question
In order to leave comments, you need to log in
Haven't coded Lua for 100 years, thanks for the nostalgia)
https://repl.it/repls/IndelibleCluelessAdmin
-- 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))
But it works for JS too
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question