如果浮点组件不是.00,则只显示小数点sprintf / printf [英] Only show decimal point if floating point component is not .00 sprintf/printf

查看:144
本文介绍了如果浮点组件不是.00,则只显示小数点sprintf / printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



Ie

$ b我相当格式化一个浮点数,但希望它显示为一个整数,如果没有相关的浮点数。
$ b

  • 1.20 - > 1.2x
    <1.77> 1.78 - > 1.78x
    < > 0.8x
  • 2.00 - > 2x



我可以通过一些正则表达式但想知道是否有一个 sprintf - 这样做的唯一方法吗?



我在Ruby中相当懒惰像这样:

 (%0.2fx%(factor / 100.0)).gsub(/\.?0+ x $ /,'x')


解决方案

使用%g 而不是%f

 %gx%(factor / 100.00)


I am pretty formatting a floating point number but want it to appear as an integer if there is no relevant floating point number.

I.e.

  • 1.20 -> 1.2x
  • 1.78 -> 1.78x
  • 0.80 -> 0.8x
  • 2.00 -> 2x

I can achieve this with a bit of regex but wondering if there is a sprintf-only way of doing this?

I am doing it rather lazily in ruby like so:

("%0.2fx" % (factor / 100.0)).gsub(/\.?0+x$/,'x')

解决方案

You want to use %g instead of %f:

"%gx" % (factor / 100.00)

这篇关于如果浮点组件不是.00,则只显示小数点sprintf / printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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