How to convert a negative number to positive?

Question:

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

Asked By: aneuryzm

||

Answers:

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

Don’t forget to check the docs.

Answered By: Roger Pate

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
Answered By: BoltClock

The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)
Answered By: Tim
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.

Answered By: Tauquir

simply multiplying by -1 works in both ways …

>>> -10 * -1
10
>>> 10 * -1
-10
Answered By: Jeroen Dierckx

If you are working with numpy you can use

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

It will provide absolute values.

Answered By: Pratik Jayarao

The inbuilt function abs() would do the trick.

n = -42
abs(n)   # for any n
42
Answered By: Muthu Raman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.