Convert floating point number to certain precision, then copy to String
I have a floating point number, say 135.12345678910
. I want to concatenate that value to a string, but only want 135.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 (eg 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 (eg 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 that f"{numvar:.9f}"
solves original problem).
使用一轮:
>>> numvar = 135.12345678910
>>> str(round(numvar,9))
'135.123456789'
>>>
Python 3.6 | 2017
Just to make it clear, you can use f-string formatting. This has almost the same syntax as the format
method, but make it a bit nicer.
Example:
print(f'{numvar:.9f}')
More reading about the new f string:
上一篇: 双倍真的不适合金钱吗?
下一篇: 将浮点数转换为某个精度,然后复制到字符串