将浮点数转换为特定精度,然后复制到字符串

pau*_*ago 129 python string floating-point

我说有一个浮点数135.12345678910.我想将该值连接到字符串,但只想要135.123456789.通过打印,我可以通过以下方式轻松完成此操作:

print "%.9f" % numvar
Run Code Online (Sandbox Code Playgroud)

numvar我的原始号码.是否有捷径可寻?

HAL*_*001 155

Python <3(例如2.6 [见注释]或2.7),有两种方法可以做到这一点.

# Option one
older_method_string = "%.9f" % numvar

# Option two
newer_method_string = "{:.9f}".format(numvar)
Run Code Online (Sandbox Code Playgroud)

但请注意,对于3以上的Python版本(例如3.2或3.3),选项2是首选.

有关选项二的更多信息,我建议使用Python文档中的字符串格式链接.

有关选项一的更多信息,此链接就足够了,并且有关于各种标志的信息.

Python 3.6(2016年12月正式发布),添加了f字符串文字,在这里查看更多信息,扩展了str.format方法(使用花括号来str.format解决原始问题),即

# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"
Run Code Online (Sandbox Code Playgroud)

解决了这个问题.查看@ Or-Duan的答案以获取更多信息,但这种方法很快.


Or *_*uan 46

Python 3.6 | 2017年

为了说清楚,你可以使用f-string格式.这与该format方法的语法几乎相同,但使它更好一些.

例:

print(f'{numvar:.9f}')
Run Code Online (Sandbox Code Playgroud)

更多关于新f字符串的阅读:

在此输入图像描述


sha*_*noo 44

使用round:

>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 7

这不是打印格式化,它是字符串的属性,所以你可以使用

newstring = "%.9f" % numvar
Run Code Online (Sandbox Code Playgroud)


Yu *_*Hao 6

如果直到运行时才知道精度,则此其他格式化选项很有用:

>>> n = 9
>>> '%.*f' % (n, numvar)
'135.123456789'
Run Code Online (Sandbox Code Playgroud)

  • 如果您更喜欢使用.format方法,请注意,也可以通过嵌套如下参数来实现:`'{:。{n} f}'。format(numvar,n = n)。 (2认同)