How to convert a negative number to positive?

2019-01-13 19:24发布

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

6条回答
Summer. ? 凉城
2楼-- · 2019-01-13 20:00
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.

查看更多
干净又极端
3楼-- · 2019-01-13 20:05
>>> n = -42
>>> -n       # if you know n is negative
42
>>> abs(n)   # for any n
42

Don't forget to check the docs.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-13 20:09

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

>>> -10 * -1
10
>>> 10 * -1
-10
查看更多
Anthone
5楼-- · 2019-01-13 20:10

The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)
查看更多
不美不萌又怎样
6楼-- · 2019-01-13 20:18

If you are working with numpy you can use

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

It will provide absolute values.

查看更多
女痞
7楼-- · 2019-01-13 20:25

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
查看更多
登录 后发表回答