D
D
dollar2019-07-31 01:14:02
JavaScript
dollar, 2019-07-31 01:14:02

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

2 answer(s)
M
Mikhail Osher, 2019-07-31
@dollar

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))

D
Denis, 2019-07-31
@Deonisius

But it works for JS too

https://jsfiddle.net/vgzah83L/
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 question

Ask a Question

731 491 924 answers to any question