2012-05-20 48 views
10

Làm thế nào tôi có thể chuyển đổi một float thành 'hình thức kế toán' của nó -Chuyển đổi phao để bằng dấu phẩy chuỗi

100028282.23 --> 100,028,282.23 
100028282 --> 100,028,282.00 

Có một phương pháp python mà thực hiện điều này?

+6

Lưu trữ số tiền bằng tiền nổi có thể không tốt như vậy ngay từ đầu. – NPE

Trả lời

14

Bạn có thể sử dụng locale.format() chức năng để làm điều này:

>>> import locale 
>>> locale.setlocale(locale.LC_ALL, 'en_US.utf8') 
'en_US.utf8' 
>>> locale.format("%.2f", 100028282.23, grouping=True) 
'100,028,282.23' 

Lưu ý rằng bạn phải từ bỏ chính xác: %.2f

Hoặc bạn có thể sử dụng locale.currency() chức năng, mà theo các LC_MONETARY cài đặt:

>>> locale.currency(100028282.23) 
'$100028282.23' 
+0

Tuyệt vời, cảm ơn! – David542

18

Thay thế cho câu trả lời tuyệt vời của beerbajay er, chuỗi đơn giản định dạng công trình trong 2.7+, mà không đòi hỏi một nhập khẩu:

>>> '{0:,.2f}'.format(24322.34) 
'24,322.34' 
3

Đối với các ứng dụng tiền tệ, thập phân module là một lựa chọn tốt cho số học dấu chấm. Để hiển thị phao thập phân bằng dấu phẩy, hãy xem công thức moneyfmt:

def moneyfmt(value, places=2, curr='', sep=',', dp='.', 
      pos='', neg='-', trailneg=''): 
    """Convert Decimal to a money formatted string. 

    places: required number of places after the decimal point 
    curr: optional currency symbol before the sign (may be blank) 
    sep:  optional grouping separator (comma, period, space, or blank) 
    dp:  decimal point indicator (comma or period) 
      only specify as blank when places is zero 
    pos:  optional sign for positive numbers: '+', space or blank 
    neg:  optional sign for negative numbers: '-', '(', space or blank 
    trailneg:optional trailing minus indicator: '-', ')', space or blank 

    >>> d = Decimal('-1234567.8901') 
    >>> moneyfmt(d, curr='$') 
    '-$1,234,567.89' 
    >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') 
    '1.234.568-' 
    >>> moneyfmt(d, curr='$', neg='(', trailneg=')') 
    '($1,234,567.89)' 
    >>> moneyfmt(Decimal(123456789), sep=' ') 
    '123 456 789.00' 
    >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') 
    '<0.02>' 

    """ 
    q = Decimal(10) ** -places  # 2 places --> '0.01' 
    sign, digits, exp = value.quantize(q).as_tuple() 
    result = [] 
    digits = map(str, digits) 
    build, next = result.append, digits.pop 
    if sign: 
     build(trailneg) 
    for i in range(places): 
     build(next() if digits else '0') 
    build(dp) 
    if not digits: 
     build('0') 
    i = 0 
    while digits: 
     build(next()) 
     i += 1 
     if i == 3 and digits: 
      i = 0 
      build(sep) 
    build(curr) 
    build(neg if sign else pos) 
    return ''.join(reversed(result)) 
Các vấn đề liên quan