pauliwago pauliwago - 7 months ago 14
Python Question

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?

Answer

With python < 3 (e.g. 2.6 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 that f"{numvar:.9f}" solves original problem).