在Python中显示一个有两位小数的浮点数 [英] Display a float with two decimal places in Python

查看:818
本文介绍了在Python中显示一个有两位小数的浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮点参数的函数(通常是整数或小数位,有一个有效数字),我需要输出一个带有两位小数的字符串(5 - > 5.00,5.5 - > 5.50等)。如何在Python中执行此操作?

解决方案

您可以使用字符串格式化运算符:

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

运算符的结果是字符串,所以你可以将它存储在一个变量,打印等。

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?

解决方案

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.

这篇关于在Python中显示一个有两位小数的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆