Python Decimal format with a minimum number of decimal places

I have multiple instances Decimalin Python. I want to format them so that

Decimal('1')       => '1.00'
Decimal('12.0')    => '12.00'
Decimal('314.1')   => '314.10'
Decimal('314.151') => '314.151'

therefore, ensuring that there are always at least two decimal places, possibly more. Although there is no shortage of solutions for rounding to ndecimal places, I cannot find clear ways to provide a lower bound on the number.

My current solution is to calculate:

first  = '{}'.format(d)
second = '{:.2f}'.format(d)

and take which one is longer. However, this seems somewhat hacky.

+5
source share
1 answer

If you want to avoid string issues:

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

Unconfirmed code, but it should work.

It works like this:

d = 12.345

Time 100:

1234.5

Minus int (1234.5)

1234.5 - 1234 = .5

.5! = 0

, 3 .

print str (12.345)

12.3405: ​​

1234.05 - 1234 =.05

.05!= 0

12.3:

1230 - 1230 = 0

, %.2f.

+2

All Articles