Python格式负货币

use*_*899 5 python formatting currency negative-number

到目前为止,我还没有找到任何解决如何格式化负货币的问题,这让我发疯。

from decimal import *
import re
import sys
import os
import locale


locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
# cBalance is a running balance of type Decimal

fBalance = locale.currency( cBalance, grouping=True )
print cBalance, fBalance
Run Code Online (Sandbox Code Playgroud)

负数结果:

-496.06 ($496.06)
Run Code Online (Sandbox Code Playgroud)

我需要一个减号而不是括号

如何去掉括号并得到减号?

小智 0

这可能不是您寻求的综合方法,但如果您使用 locale en_US.UTF-8,您可以使用带有负号的确定性方法-

import locale
locale.setlocale(locale.LC_ALL, b'en_US.UTF-8')

amount = locale.currency(-350, grouping=True)
print(amount) # -$350.00

amount = locale.currency(-350, grouping=True).replace('$', '')
print(amount) # -350.00
Run Code Online (Sandbox Code Playgroud)