How can I convert a negative number to positive in Python? (And keep a positive one.)
            Asked
            
        
        
            Active
            
        
            Viewed 4.2e+01k times
        
    144
            
            
        - 
                    Reading the original question (or the return to the original phrasing if [the edit](http://stackoverflow.com/review/suggested-edits/10741589) gets approved), it's unclear what your parenthesized sentence was supposed to mean. Did you mean you wanted to keep a copy of the original, or did you mean that you wanted to leave positive values unmodified? – jpmc26 Dec 31 '15 at 21:04
7 Answers
289
            >>> n = -42
>>> -n       # if you know n is negative
42
>>> abs(n)   # for any n
42
Don't forget to check the docs.
- 
                    9
- 
                    12`max` is a neat trick, but, especially in python, there is an overhead to it, which will be 30% slower than `abs`. So you should definitely prefer `abs` over `max` – user1767754 Nov 19 '17 at 04:21
- 
                    1you have to store it in a variable you know...(I got a huge mess because of that!!!!) – Boruto Uzumaki Nov 02 '21 at 16:16
90
            
            
        simply multiplying by -1 works in both ways ...
>>> -10 * -1
10
>>> 10 * -1
-10
 
    
    
        Jeroen Dierckx
        
- 1,570
- 1
- 15
- 27
- 
                    3This would be the simplest solution I guess. This solution would convert negative to positive and positive to negative number. – Naveen Raju May 15 '20 at 19:06
- 
                    4
42
            
            
        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
 
    
    
        user1767754
        
- 23,311
- 18
- 141
- 164
 
    
    
        BoltClock
        
- 700,868
- 160
- 1,392
- 1,356
8
            
            
        If you are working with numpy you can use
import numpy as np
np.abs(-1.23)
>> 1.23
It will provide absolute values.
 
    
    
        Pratik Jayarao
        
- 89
- 1
- 1
- 
                    While true, I can't think of a situation in which this would be preferred to Python's native `abs` function. – xavdid Jan 30 '23 at 06:27
7
            
            
        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.
 
     
     
     
     
    