Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

python - variable number of digit in format string

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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%'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...