'Rounding negative numbers to the nearest 1,000 that is closest to zero
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
Solution 1:[1]
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)
Solution 2:[2]
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
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | wovano |
Solution 2 | |
Solution 3 |