Basically to remove digits from a float to have a fixed number of digits after the dot, like:
1.923328437452 -> 1.923
EDIT: I need to output as a string to another function, not print.
Also I want to ignore the lost digits, not round them.
Basically to remove digits from a float to have a fixed number of digits after the dot, like:
1.923328437452 -> 1.923
EDIT: I need to output as a string to another function, not print.
Also I want to ignore the lost digits, not round them.
round(1.923328437452, 3)
Python standard types, you'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to.
If you mean when printing, then the following should work:
print '%.3f' % number
The result of round
is a float, so watch out:
>>> round(1.923328437452, 3)
1.923
>>> round(1.23456, 3)
1.2350000000000001
You will be better off when using a formatted string:
>>> "%.3f" % 1.923328437452
'1.923'
>>> "%.3f" % 1.23456
'1.235'
I would convert to a string at full precision and then just chop off everything but the first so many characters.
def trunc(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
slen = len('%.*f' % (n, f))
return str(f)[:slen]
(edited to fix bugs)
In response to your comment: the version above doesn't include the zeros, but here's my old version that did:
def trunc(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
return ('%.*f' % (n + 1, f))[:-1]
The latter does fail on some corner cases, though, like trunc(11.999999, 3)
def trunc(num, digits):
sp = str(num).split('.')
return '.'.join([sp[0], sp[:digits]])
This should work. It should give you the truncation you are looking for.
Just wanted to mention that the old "make round() with floor()" trick of
round(f) = floor(f+0.5)
can be turned around to make floor() from round()
floor(f) = round(f-0.5)
Although both these rules break around negative numbers, so using it is less than ideal:
def trunc(f, n):
if f > 0:
return "%.*f" % (n, (f - 0.5*10**-n))
elif f == 0:
return "%.*f" % (n, f)
elif f < 0:
return "%.*f" % (n, (f + 0.5*10**-n))