144

How can I convert a negative number to positive in Python? (And keep a positive one.)

Oliver Goodman
  • 671
  • 6
  • 14
aneuryzm
  • 63,052
  • 100
  • 273
  • 488
  • Reading the original question (or the return to the original phrasing if [the edit](http://stackoverflow.com/review/suggested-edits/10741589) 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? – jpmc26 Dec 31 '15 at 21:04

7 Answers7

289
>>> n = -42
>>> -n       # if you know n is negative
42
>>> abs(n)   # for any n
42

Don't forget to check the docs.

90

simply multiplying by -1 works in both ways ...

>>> -10 * -1
10
>>> 10 * -1
-10
Jeroen Dierckx
  • 1,570
  • 1
  • 15
  • 27
42

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
user1767754
  • 23,311
  • 18
  • 141
  • 164
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
17

The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)
Tim
  • 5,732
  • 2
  • 27
  • 35
8

If you are working with numpy you can use

import numpy as np
np.abs(-1.23)
>> 1.23

It will provide absolute values.

  • While true, I can't think of a situation in which this would be preferred to Python's native `abs` function. – xavdid Jan 30 '23 at 06:27
7
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.

tzot
  • 92,761
  • 29
  • 141
  • 204
Tauquir
  • 6,613
  • 7
  • 37
  • 48
0

The inbuilt function abs() would do the trick.

n = -42
abs(n)   # for any n
42