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?
asked Mar 7, 2013 at 5:14
1
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 information on option two, I suggest this link on string formatting from the Python documentation.
And for more information on option one, this link will suffice and has info on the various flags.
Python 3.6 [officially released in December of 2016], added the f
string literal, see more information
here, which extends the str.format
method [use of curly braces such that f"{numvar:.9f}"
solves the original problem], that is,
# Option 3 [versions 3.6 and higher]
newest_method_string = f"{numvar:.9f}"
solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.
answered Mar 7, 2013 at 5:36
jyalimjyalim
3,1731 gold badge14 silver badges22 bronze badges
4
Using round
:
>>> numvar = 135.12345678910
>>> str[round[numvar, 9]]
'135.123456789'
answered Mar 7, 2013 at 5:33
shantanooshantanoo
3,5871 gold badge23 silver badges36 bronze badges
0
In case the precision is not known until runtime, this other formatting option is useful:
>>> n = 9
>>> '%.*f' % [n, numvar]
'135.123456789'
answered Aug 17, 2015 at 7:04
Yu HaoYu Hao
117k43 gold badges227 silver badges283 bronze badges
1
It's not print that does the formatting, It's a property of strings, so you can just use
newstring = "%.9f" % numvar
answered Mar 7, 2013 at 5:19
John La RooyJohn La Rooy
286k51 gold badges358 silver badges498 bronze badges
1
To set precision with 9 digits, get:
print "%.9f" % numvar
Return precision with 2 digits:
print "%.2f" % numvar
Return precision with 2 digits and float converted value:
numvar = 4.2345
print float["%.2f" % numvar]
Eric Aya
69.1k34 gold badges176 silver badges245 bronze badges
answered Jan 18, 2018 at 8:13
Tejas TankTejas Tank
1,0442 gold badges14 silver badges27 bronze badges
The str
function has a bug. Please try the following. You will see '0,196553' but the right output is '0,196554'. Because the str
function's default value is ROUND_HALF_UP.
>>> value=0.196553500000
>>> str["%f" % value].replace[".", ","]
answered Nov 9, 2015 at 16:33
ethemsulanethemsulan
2,20126 silver badges19 bronze badges
2