188

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pauliwago
  • 6,373
  • 11
  • 42
  • 52
  • 3
    % exactly does that - % is not part of the print function but of string - see [Python docs](http://docs.python.org/2/library/stdtypes.html#string-formatting-operations) – michael_s Mar 07 '13 at 05:21

8 Answers8

247

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.

jyalim
  • 3,289
  • 1
  • 15
  • 22
  • 1
    option two should be `newer_method_string = "{:.9f}".format(numvar)` - note the required `:` to separate the field and the formatting. I have tested this on 2.7.5 anyway. – Caltor Nov 04 '13 at 14:29
  • 1
    For python 2.6 option two should be `newer_method_string = "{0:.9f}".format(numvar)` -- note the required 0 for the field_name for this older version. – ttq Oct 26 '16 at 15:26
  • I want significant figures not just truncating blindly t according to `{v.:3f}`. How do I get significant figures? – Charlie Parker Feb 16 '21 at 23:22
  • @CharlieParker I'd recommend using exponential notation, for example `{:12.5e}`. There's more in this subsection of the documentation (https://docs.python.org/2/library/string.html#format-specification-mini-language). – jyalim Feb 24 '21 at 01:16
78

Python 3.6

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

execution times

fantabolous
  • 21,470
  • 7
  • 54
  • 51
Or Duan
  • 13,142
  • 6
  • 60
  • 65
62

Using round:

>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'
Vishvajit Pathak
  • 3,351
  • 1
  • 21
  • 16
shantanoo
  • 3,617
  • 1
  • 24
  • 37
12

In case the precision is not known until runtime, this other formatting option is useful:

>>> n = 9
>>> '%.*f' % (n, numvar)
'135.123456789'
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 6
    If you'd prefer to use `.format`-method, note that this can also be done by nesting arguments like so: `'{:.{n}f}'.format(numvar,n=n)`. – nivk Oct 29 '18 at 20:42
8

It's not print that does the formatting, It's a property of strings, so you can just use

newstring = "%.9f" % numvar
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

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,473
  • 35
  • 181
  • 253
Tejas Tank
  • 1,100
  • 2
  • 16
  • 28
0

It works as long as the number of decimals points are in range; After that it depends on the hardware. Beyond 14th decimal place, I could not get it to match. Values from latitude from a digital elevation file

https://docs.python.org/3/tutorial/floatingpoint.html

lat1 = -81.0016666666670072 
lat2 = -81.0016666666670062
assert lat1 == lat2 # no asserion error :(

# try with Decimal
from decimal import *
getcontext().prec = 16
assert Decimal(lat1) == Decimal(lat2) # no asserion error :(

# Lets see string representation
print(f"{lat1:.16f}", f"{lat2:.16f}")
# -81.0016666666670062 -81.0016666666670062 :( Perils of Float

# Lets see how it is store in hardware
print(lat1.hex(), lat2.hex())
# -0x1.4401b4e81b500p+6 -0x1.4401b4e81b500p+6

# 14-th position it is able to identify 
lat1 = -81.0016666666670162 
lat2 = -81.0016666666670062
#-0x1.4401b4e81b501p+6 -0x1.4401b4e81b500p+6
print(lat1.hex(), lat2.hex())
assert lat1 == lat2 # assertion error :)
Alex Punnen
  • 5,287
  • 3
  • 59
  • 71
-2

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(".", ",")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ethemsulan
  • 2,241
  • 27
  • 19