pauliwago pauliwago - 1 year ago 82
Python Question

Convert floating point number to certain precision, then copy to String

I have a floating point number, say

. I want to concatenate that value to a string, but only want
. With print, I can easily do this by doing something like:

print "%.9f" % numvar

being my original number. Is there an easy way to do this?

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download