How to use Python string formatting to convert an integer representing cents to a float representing dollars?

后端 未结 3 1383
谎友^
谎友^ 2020-12-10 17:31

I have an integer representing a price in cents. Using Python format strings, how can I convert this value into dollars with two decimal places? Examples:

         


        
相关标签:
3条回答
  • 2020-12-10 17:58

    You should try hard to avoid ever using floats to represent money (numerical inaccuracy can too easily creep in). The decimal module provides a useful datatype for representing money as it can exactly represent decimal numbers such as 0.05.

    It can be used like this:

    import decimal
    cents = 999
    dollars = decimal.Decimal(cents) / 100
    print dollars
    
    0 讨论(0)
  • 2020-12-10 18:06

    If you don't care about localization, then simply divide by 100 and format it:

    >>> for cents in [ 1234, 5, 999 ]:
    ...     '{0:.02f}'.format(float(cents) / 100.0)
    ...
    '12.34'
    '0.05'
    '9.99'
    

    If you do care about localization, then use the locale module:

    >>> import locale
    >>> locale.setlocale(locale.LC_ALL, "") # use the user-default locale
    'en_US.UTF-8'
    >>> for cents in [ 1234, 5, 999 ]:
    ...     locale.currency(float(cents) / 100.0)
    ...
    '$12.34'
    '$0.05'
    '$9.99'
    
    0 讨论(0)
  • 2020-12-10 18:14

    Using str.format:

    for i in (1234,5,999):
        print('{:.2f}'.format(i/100.))
    

    yields

    12.34
    0.05
    9.99
    

    In Python2.6 use '{0:.2f}' instead of '{:.2f}'.

    0 讨论(0)
提交回复
热议问题