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

Time:05-12

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

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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