How to convert a negative number to positive?

与世无争的帅哥 提交于 2019-11-26 15:44:27

问题


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


回答1:


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

Don't forget to check the docs.




回答2:


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

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



回答3:


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



回答4:


The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)



回答5:


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.




回答6:


If you are working with numpy you can use

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

It will provide absolute values.



来源:https://stackoverflow.com/questions/3854310/how-to-convert-a-negative-number-to-positive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!