Home > database >  Negative percentages in Python 3
Negative percentages in Python 3

Time:08-28

-5 is a greater negative than -3. How can I express this change in Python 3 as a continuing negative and STILL KEEP the negative sign? (-5 divided by -3 (rounded) computes as 1.67)

CodePudding user response:

Mathematically, a negative number divided by a negative number is a positive number.

However, if you want to preserve the sign, you can use math.copysign:

import math

a = -5
b = -3

# Divides `a` and `b` preserving the sign of `a`
print(math.copysign(a / b, a))    # -1.6666666666666667

CodePudding user response:

Assuming a and b will always be negative, you can multiply one of them with -1:

a = -5
b = -3

return round(a/(b*-1))

If not always negative, you can use if to check:

if (a && b) < 0:
  return round(a/(b*-1))

return round(a/b)
  • Related