将负数四舍五入到最接近零的 1,000

Rounding negative numbers to the nearest 1,000 that is closest to zero

我希望将数字四舍五入到最接近零的 1,000。以下代码适用于正数

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

然而,当我在负数上使用代码时,它会移动得更远。

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

这对正数和负数都有效。

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)

输出

IN:-1254, OUT:-1000
IN:-1500, OUT: -1000
IN:-1501, OUT: -1000

您可以只使用四舍五入的数字的绝对值,然后使用 math.copysign()

保留数字的符号
import math
original_number = -1800
new_number = math.copysign(abs(original_number) // 1000 * 1000, original_number)
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)