Display a float with two decimal places in Python

前端 未结 11 2255
我在风中等你
我在风中等你 2020-11-22 14:36

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

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 14:44

    f-string formatting:

    This was 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.

    >>> foobar = 3.141592
    >>> print(f'My number is {foobar:.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 foobar can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.

    Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.

提交回复
热议问题