2

I'm looking to round numbers to their nearest 1,000 closest to zero. The following code works for positive numbers

import math
original_number = 1245
new_number = math.floor(original_number / 1000.00) * 1000
>> 1000

However, when I use the code on negative numbers it moves further away.

import math
original_number = -1245
new_number = math.floor(original_number / 1000.00) * 1000
>> -2000
Jody
  • 115
  • 5

3 Answers3

4

You can just use the absolute value of the number you are rounding, then preserve the sign of your number using math.copysign(),

import math
original_number = -1800
new_number = math.copysign(abs(original_number) // 1000 * 1000, original_number)
wovano
  • 4,543
  • 5
  • 22
  • 49
atru
  • 4,699
  • 2
  • 18
  • 19
1

This works for both positive and negative number.

import math
original_number = -1100
if original_number<0:
    new_number = -math.floor(abs(original_number) / 1000.00) * 1000
else:
    new_number = math.floor(original_number / 1000.00) * 1000
print(new_number)

OUTPUT

IN:-1254, OUT:-1000
IN:-1500, OUT: -1000
IN:-1501, OUT: -1000
codester_09
  • 5,622
  • 2
  • 5
  • 27
1
round_thousands_towards_zero = lambda num: num - (num % (num/abs(num)*1000))

lambdaless:

def round_thousands_towards_zero(num):
    sign = num/abs(num)
    saught_multiplier = sign * 1000
    return num - (num % saught_multiplier)
Lukas Schmid
  • 1,895
  • 1
  • 6
  • 18
  • 2
    Why are you using a lambda for this? One-liners are not always better. The official Python Style Guide says the following about this: "_Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier_". The function itself looks nice though. – wovano May 11 '22 at 11:49
  • I prefer writing single-operator, math-only functions as lambdas, but I added a more verbose version now – Lukas Schmid May 11 '22 at 13:58
  • You could still `return num - (num % (num/abs(num)*1000))` inside the function. There's just no point in creating a lambda function and then assigning it to a variable (except for reducing your line count by 1). – wovano May 11 '22 at 14:28