How to convert a negative number to positive?

Each Answer to this Q is separated by one/two green lines.

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

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

Don’t forget to check the docs.

simply multiplying by -1 works in both ways …

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

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)
>>> abs(1)

The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)

If you are working with numpy you can use

import numpy as np
>> 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.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.