How can I convert a negative number to positive in Python? (And keep a positive one.)
-
Reading the original question (or the return to the original phrasing if the edit gets approved), it's unclear what your parenthesized sentence was supposed to mean. Did you mean you wanted to keep a copy of the original, or did you mean that you wanted to leave positive values unmodified?– jpmc26Dec 31, 2015 at 21:04
6 Answers
>>> n = -42
>>> -n # if you know n is negative
42
>>> abs(n) # for any n
42
Don't forget to check the docs.
-
9
-
12
max
is a neat trick, but, especially in python, there is an overhead to it, which will be 30% slower thanabs
. So you should definitely preferabs
overmax
Nov 19, 2017 at 4:21 -
1you have to store it in a variable you know...(I got a huge mess because of that!!!!) Nov 2, 2021 at 16:16
simply multiplying by -1 works in both ways ...
>>> -10 * -1
10
>>> 10 * -1
-10
-
3This would be the simplest solution I guess. This solution would convert negative to positive and positive to negative number. May 15, 2020 at 19:06
-
4
If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use abs()
:
>>> abs(-1)
1
>>> abs(1)
1
If you are working with numpy you can use
import numpy as np
np.abs(-1.23)
>> 1.23
It will provide absolute values.
In [6]: x = -2
In [7]: x
Out[7]: -2
In [8]: abs(x)
Out[8]: 2
Actually abs
will return the absolute value
of any number. Absolute value is always a non-negative number.
-
2Does abs(0) return a positive number? :)– Roger PateOct 4, 2010 at 23:18