Python字符串插值:只显示必要的小数位数 [英] Python string interpolation: only show necessary decimal places

查看:188
本文介绍了Python字符串插值:只显示必要的小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有例如x = 40,我想要下面的结果:

  40

对于x = 2.5,结果应该是...



<$ p $所以我基本上想格式化到最多一位小数地点。我现在使用这个:

$ $ p $ $ code $ {0:0.1f} \。格式(x,1)

但是,这总是显示一个小数位,这不是我真正想要的...

解决方案



  {0} \。format(str(round(x,1)if x%1 else int(x)))

如果没有小数部分,将显示 x 作为整数。这很有可能是一个更好的办法。


If I have for example x = 40 I want the following result:

40"

For x = 2.5 the result should be like...

2.5"

So I basically want to format to at most one decimal place. I currently use this:

"{0:0.1f}\"".format(x, 1)

But this displays always exactly one decimal place, which is not really what I want...

解决方案

One option is something like

"{0}\"".format(str(round(x, 1) if x % 1 else int(x)))

which will display x as an integer if there's no fractional part. There's quite possibly a better way to go about this.

这篇关于Python字符串插值:只显示必要的小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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