How to convert a negative number to positive?

PythonNumbersAbsolute Value

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Don't forget to check the docs.

Solution 2 - Python

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

>>> -10 * -1
10
>>> 10 * -1
-10

Solution 3 - Python

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

Solution 4 - Python

The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)

Solution 5 - Python

If you are working with numpy you can use

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

It will provide absolute values.

Solution 6 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaneuryzmView Question on Stackoverflow
Solution 1 - PythonRoger PateView Answer on Stackoverflow
Solution 2 - PythonJeroen DierckxView Answer on Stackoverflow
Solution 3 - PythonBoltClockView Answer on Stackoverflow
Solution 4 - PythonTimView Answer on Stackoverflow
Solution 5 - PythonPratik JayaraoView Answer on Stackoverflow
Solution 6 - PythonTauquirView Answer on Stackoverflow