Python Format Decimal with a minimum number of Decimal Places

前端 未结 1 1162
面向向阳花
面向向阳花 2020-12-20 16:12

I have some Decimal instances in Python. I wish to format them such that

Decimal(\'1\')       => \'1.00\'
Decimal(\'12.0\')    => \'12.00         


        
相关标签:
1条回答
  • 2020-12-20 16:34

    If you wish to avoid string issues:

    if d*100 - int(d*100):
        print str(d)
    else:
        print ".2f" % d
    

    Untested code, but it should work.

    This works like so:

    d = 12.345

    Times 100:

    1234.5

    Minus int(1234.5)

    1234.5 - 1234 = .5

    .5 != 0

    This means that there are 3 or more decimal places.

    print str(12.345)

    Even if you do 12.3405:

    1234.05 - 1234 = .05

    .05 != 0

    But if you have 12.3:

    1230 - 1230 = 0

    This means to print with %.2f.

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