【问题标题】:Python: How do I approximate a float when I convert to string?Python:转换为字符串时如何近似浮点数?
【发布时间】:2012-10-19 15:07:37
【问题描述】:

我有一个计时模块:

start_timing = time.time()
#stuff happening here    
report_timing["INT_MODULE"] = time.time()- start_timing

如果我使用str(report_timing["INT_MODULE"]),我得到的是很长的:0.000441074371338

有没有一种标准方法可以将此浮点数四舍五入为0.0004 或以其他方式表示为更少的数字,如@9​​87654327@,换句话说,一种转换时间的标准方法?

【问题讨论】:

标签: python string floating-point python-2.7


【解决方案1】:

你可以尝试一些字符串格式:

In [1]: strs=0.000441074371338

In [2]: "{0:e}".format(strs)
Out[2]: '4.410744e-04'

In [3]: "{0:.4f}".format(strs)
Out[3]: '0.0004'

In [9]: "{0:.0f} us".format(strs*1000*1000)
Out[9]: '441 us'

【讨论】:

    【解决方案2】:

    report_timing["INT_MODULE"] = int((time.time() - start_timing)*1000.0) / 1000

    【讨论】:

      【解决方案3】:

      您可以使用默认的内置函数对 long 进行舍入; http://docs.python.org/2/library/functions.html#round

      至于换算成微秒,我怕是帮不上忙了。

      【讨论】:

        猜你喜欢
        • 2011-11-25
        • 2019-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-15
        • 2011-12-18
        • 1970-01-01
        相关资源
        最近更新 更多