Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading