Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: format negative number with parentheses

Tags:

python

Is there a way to use either string interpolation or string.format to render negative numbers into text formatted using parentheses instead of "negative signs"?

I.e. -3.14 should be (3.14).

I had hoped to do this using string interpolation or string.format rather than needing an import specifically designed for currencies or accounting.

Edit to clarify: Please assume the variable to be formatted is either an int or a float. I.e. while this can be done with regular expressions (see good answers below), I was thinking this would be a more native operation for Python's formatting functionality.

So to be clear:

import numpy as np
list_of_inputs = [-10, -10.5, -10 * np.sqrt(2), 10, 10.5, 10 * np.sqrt(2)]
for i in list_of_inputs:
    # your awesome solution goes here

should return:

(10)
(10.5)
(14.14)
10
10.5
14.14

Clearly there is some flexibility about that last one. I had hoped the "put negative numbers in parentheses" would be a natural argument of string interpolation or string.format so that I could use other formatting language while setting the display style of negative numbers.

like image 409
8one6 Avatar asked Apr 23 '26 18:04

8one6


1 Answers

If you just need to handle possibly-negative numeric input:

print '{0:.2f}'.format(num) if num>=0 else '({0:.2f})'.format(abs(num))
like image 144
tzaman Avatar answered Apr 27 '26 10:04

tzaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!