将浮点数转换为某个精度,然后复制到String [英] Convert floating point number to certain precision, then copy to String
问题描述
我有一个浮点数,例如 135.12345678910
。我想将该值连接到一个字符串,但只需要 135.123456789
。打印,我可以很容易做到这一点:
print%.9f%numvar
与 numvar
是我的原始编号。有没有一个简单的方法来做到这一点?
使用python< 3(例如2.6 [见注释]或2.7),有两种方法可以做到。
#Option 1
但是请注意,对于Python版本高于3(例如3.2或3.3),选项二是首选项。
old_method_string =%.9f%numvar
#选项二
newer_method_string ={:.9f}。格式(numvar)
有关选项2的更多信息, 这个链接来自python文档的字符串格式。
有关选项1的更多信息,请参阅更新:Python 3.6(2016年12月正式发布),将添加
f
字符串字符串,在这里查看更多信息,它扩展了str.format方法(使用大括号,使得f{numvar: .9f}
解决了原来的问题。)I have a floating point number, say
135.12345678910
. I want to concatenate that value to a string, but only want135.123456789
. With print, I can easily do this by doing something like:print "%.9f" % numvar
with
numvar
being my original number. Is there an easy way to do this?解决方案With python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.
# Option one older_method_string = "%.9f" % numvar # Option two newer_method_string = "{:.9f}".format(numvar)
But note that for python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.
For more info on option two, I suggest this link on string formatting from the python docs.
And for more info on option one, this link will suffice and has info on the various flags.
UPDATE: Python 3.6 (official release in December of 2016), will add the
f
string literal, see more info here, which extends the str.format method (use of curly braces such thatf"{numvar:.9f}"
solves original problem).这篇关于将浮点数转换为某个精度,然后复制到String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!