Display a float with two decimal places in Python

前端 未结 11 2195
我在风中等你
我在风中等你 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:42

    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.

提交回复
热议问题