【问题标题】:Casting float to string without scientific notation在没有科学记数法的情况下将浮点数转换为字符串
【发布时间】:2014-09-04 12:27:56
【问题描述】:

浮动:

fl = 0.000005

将String 转换为str(fl)=='5e-06'。但是,我希望它转换为 str(fl)='0.000005' 以导出到 CSV 目的。

我如何做到这一点?

【问题讨论】:

  • 您需要使用str() 还是可以使用'{:f}'.format(fl) 之类的东西?
  • 正如 grc 所说,"{:f}".format(fl) 会做你想做的事
  • @PadraicCunningham @grc 我得到异常Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: zero length field name in format
  • 什么版本的python? "{0:f}".format(fl) 有效吗?
  • 或许'{0:.16f}'.format(fl).rstrip('0')?

标签: python string casting double scientific-notation


【解决方案1】:

您可以只使用标准字符串格式选项来说明您想要的精度

>>> fl = 0.000005
>>> print '%.6f' % fl
0.000005

【讨论】:

  • 如果我只希望它达到我指定fl 的精确度怎么办。所以如果我设置fl = 0.00214,我想要string = '0.00214',或者如果我设置fl = 0.0000000006,我想要string = '0.0000000006'。
【解决方案2】:

使用

fl = 0.00005
s = '%8.5f' % fl
print s, type(s)

给予

0.00005 <type 'str'>

如果您不需要额外的数字,请使用 %g(尽管它使用指数表示法,例如 0.000005)。例如:

fl = 0.0005
s = '%g' % fl
print s, type(s)

fl = 0.005
s = '%g' % fl
print s, type(s)

给予

0.0005 <type 'str'>
0.005 <type 'str'>

【讨论】:

  • %g 将为 0.000005 等数字提供科学记数法。顺便说一句,不需要您的 str 电话。
  • @interjay 感谢您的评论,我相应地更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 2014-09-25
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多