如何显示带有两位小数的浮点数? [英] How to display a float with two decimal places?

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

问题描述

我有一个带浮点参数的函数(通常是整数或带一位有效数字的小数),我需要输出带有两位小数(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.

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

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