Display a float with two decimal places in Python

2019-01-02 15:31发布

I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 -> 5.00, 5.5 -> 5.50, etc). How can I do this in Python?

6条回答
与风俱净
2楼-- · 2019-01-02 16:09

f-string formatting:

This is new in Python 3.6 - the string is placed in quotation marks as usual, prepended with f'... in the same way you would r'... for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text' - and Python evaluates as with previous string formatting methods, except that this method is much more readable.

>>>a = 3.141592
>>>print(f'My number is {a:.2f} - look at the nice rounding!')

My number is 3.14 - look at the nice rounding!

You can see in this example we format with decimal places in similar fashion to previous string formatting methods.

NB a can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.

Going forward, with new code f-strings should be preferred over common %s or str.format() methods as f-strings are much faster.

查看更多
一个人的天荒地老
3楼-- · 2019-01-02 16:15

Since this post might be here for a while, lets also point out python 3 syntax:

"{:.2f}".format(5)
查看更多
浮光初槿花落
4楼-- · 2019-01-02 16:17

You could use the string formatting operator for that:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

The result of the operator is a string, so you can store it in a variable, print etc.

查看更多
君临天下
5楼-- · 2019-01-02 16:18

String formatting:

print "%.2f" % 5
查看更多
深知你不懂我心
6楼-- · 2019-01-02 16:30

Using Python 3 syntax:

print('%.2f' % number)
查看更多
大哥的爱人
7楼-- · 2019-01-02 16:31

Using python string formatting.

>>> "%0.2f" % 3
'3.00'
查看更多
登录 后发表回答