打印不带前导零的浮点值 [英] Print floating point values without leading zero

查看:52
本文介绍了打印不带前导零的浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用格式说明符打印一个小于 1 且没有前导零的浮点数.我想出了一些技巧,但我认为有一种方法可以删除格式说明符中的前导零.我在文档中找不到它.

问题

<预><代码>>>>k = .1337>>>打印 "%.4f" % k'0.1337'

破解

<预><代码>>>>打印 ("%.4f" % k) [1:]'.1337'

解决方案

尽管我喜欢可爱的正则表达式技巧,但我认为一个简单的函数是最好的方法:

def formatFloat(fmt, val):ret = fmt % val如果 ret.startswith("0."):返回 ret[1:]如果 ret.startswith("-0."):返回 "-" + ret[2:]返回 ret>>>formatFloat("%.4f", .2)'.2000'>>>formatFloat("%.4f", -.2)'-.2000'>>>formatFloat("%.4f", -100.2)'-100.2000'>>>formatFloat("%.4f", 100.2)'100.2000'

这样做的好处是易于理解,部分原因是 startswith 是一个简单的字符串匹配而不是正则表达式.

Trying to use a format specifier to print a float that will be less than 1 without the leading zero. I came up with a bit of a hack but I assume there is a way to just drop the leading zero in the format specifier. I couldn't find it in the docs.

Issue

>>> k = .1337
>>> print "%.4f" % k
'0.1337'

Hack

>>> print ("%.4f" % k) [1:]
'.1337'

解决方案

As much as I like cute regex tricks, I think a straightforward function is the best way to do this:

def formatFloat(fmt, val):
  ret = fmt % val
  if ret.startswith("0."):
    return ret[1:]
  if ret.startswith("-0."):
    return "-" + ret[2:]
  return ret

>>> formatFloat("%.4f", .2)
'.2000'
>>> formatFloat("%.4f", -.2)
'-.2000'
>>> formatFloat("%.4f", -100.2)
'-100.2000'
>>> formatFloat("%.4f", 100.2)
'100.2000'

This has the benefit of being easy to understand, partially because startswith is a simple string match rather than a regex.

这篇关于打印不带前导零的浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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