How do I get 1324343032.324?
As you can see below, the following do not work:
>>1324343032.324325235 * 1000 / 1000
1324343032.3243253
>>i
Maybe python changed since this question, all of the below seem to work well
Python2.7
int(1324343032.324325235 * 1000) / 1000.0
float(int(1324343032.324325235 * 1000)) / 1000
round(int(1324343032.324325235 * 1000) / 1000.0,3)
# result for all of the above is 1324343032.324
How about this:
In [1]: '%.3f' % round(1324343032.324325235 * 1000 / 1000,3)
Out[1]: '1324343032.324'
Possible duplicate of round() in Python doesn't seem to be rounding properly
[EDIT]
Given the additional comments I believe you'll want to do:
In : Decimal('%.3f' % (1324343032.324325235 * 1000 / 1000))
Out: Decimal('1324343032.324')
The floating point accuracy isn't going to be what you want:
In : 3.324
Out: 3.3239999999999998
(all examples are with Python 2.6.5)
You can use an additional float()
around it if you want to preserve it as a float
.
%.3f'%(1324343032.324325235)
I suggest next solution:
def my_floor(num, precision):
return f'{num:.{precision+1}f}'[:-1]
my_floor(1.026456,2) # 1.02
Use the decimal module. But if you must use floats and still somehow coerce them into a given number of decimal points converting to string an back provides a (rather clumsy, I'm afraid) method of doing it.
>>> q = 1324343032.324325235 * 1000 / 1000
>>> a = "%.3f" % q
>>> a
'1324343032.324'
>>> b = float(a)
>>> b
1324343032.324
So:
float("%3.f" % q)
Maybe this way:
def myTrunc(theNumber, theDigits):
myDigits = 10 ** theDigits
return (int(theNumber * myDigits) / myDigits)