Reputation: 10162
Which is a clean way to write this formatting function:
def percent(value,digits=0):
return ('{0:.%d%%}' % digits).format(value)
>>> percent(0.1565)
'16%'
>>> percent(0.1565,2)
'15.65%'
the problem is formatting a number with a given number of digits, I don't like to use both '%' operator and format method.
Upvotes: 16
Views: 5586
Reputation: 212835
I like this one:
'{0:.{1}%}'.format(value, digits)
Test:
>> '{0:.{1}%}'.format(0.1565, 0)
'16%'
>> '{0:.{1}%}'.format(0.1565, 2)
'15.65%'
Upvotes: 38
Reputation: 90742
*
does what you want, for printf
-style string formatting.
>>> def percent(value, digits=0):
... return '%.*f%%' % (digits, value * 100)
...
>>> percent(0.1565, 2)
'15.65%'
Advanced string formatting (defined in PEP 3101 and documented in 7.1.3. Format String Syntax) doesn't seem to be capable of doing this in one pass. (See 7.1.3.1. Format Specification Mini-Language: precision
is integer
only.)
Upvotes: 3
Reputation: 43437
From the docs:
Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
Example:
def percent(value, digits=0):
print '%.*f%%' % (digits, value*100)
>>> percent(0.1565, 2)
15.65%
Upvotes: 2