Home  >  Q&A  >  body text

python如何相加加法

#<type 'unicode'>
a = '276.30'
b = '1,446.90'
c = '23,456.80'

相加之后,保留2个小数点~

怪我咯怪我咯2741 days ago543

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:32:43

    >>> num=['276.30','1,446.90','23,456.80']
    >>> "%.2f" % sum(map(lambda s:float(s.replace(',','')),num))
    '25180.00'
    

    >>> '{:,.2f}'.format(sum(map(lambda s:float(s.replace(',','')),num)))
    '25,180.00'
    

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:32:43

    http://stackoverflow.com/ques...

    reply
    0
  • 阿神

    阿神2017-04-18 10:32:43

    >>> def sum(*args):
    ...     r = 0.0
    ...     for n in args:
    ...             r += float(n)
    ...     return "%.2f" % r
    ...
    >>> sum('1.1', '2.2')
    '3.30'
    >>> sum('1.1', '2.2', 3.3)
    '6.60'

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:32:43

    It depends on whether you need the displayed value with two decimal places or the real addition with two decimal places.
    The former is

    ans_print_version = "{.2f}".format(a + b + c)

    The latter is

    ans = round(a + b + c,2)

    reply
    0
  • Cancelreply