用 f 字符串固定小数点后的数字 [英] Fixed digits after decimal with f-strings

查看:19
本文介绍了用 f 字符串固定小数点后的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python f-strings 是否有一种简单的方法来修复小数点后的位数?(特别是 f 字符串,而不是其他字符串格式选项,如 .format 或 %)

例如,假设我想在小数点后显示 2 位数字.

我该怎么做?说吧

a = 10.1234

解决方案

在格式表达式中包含类型说明符:

<预><代码>>>>a = 10.1234>>>f'{a:.2f}''10.12'

Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %)

For example, let's say I want to display 2 digits after the decimal place.

How do I do that? Let's say that

a = 10.1234

解决方案

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

这篇关于用 f 字符串固定小数点后的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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