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?
This question is related to
python
string
floating-point
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:
Here is a diagram of the execution times of the various tested methods (from last link above):
Using round
:
>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'
In case the precision is not known until runtime, this other formatting option is useful:
>>> n = 9
>>> '%.*f' % (n, numvar)
'135.123456789'
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(".", ",")
It's not print that does the formatting, It's a property of strings, so you can just use
newstring = "%.9f" % numvar
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)
Source: Stackoverflow.com