For rounding to the nearest 0.05, I am just dividing it by 0.05 and then multiply by 0.05. As described in other similar questions.
In [119]: (127.651//0.05)*0.05
Out[119]: 127.65
In [120]: (127.6501//0.05)*0.05
Out[120]: 127.65
In [121]: (127.65000001//0.05)*0.05
Out[121]: 127.65
In [122]: (127.65000000001//0.05)*0.05
Out[122]: 127.65
In [123]: (127.6500000000001//0.05)*0.05
Out[123]: 127.65
Till here its doing as expected. However for this special case:
In [124]: (127.650000000000000001//0.05)*0.05
Out[124]: 127.60000000000001
I would have expected 127.65 here.
Tried rounding off before dividing, but again.. strange. Not only i am getting unexpected result(expecting 127.65), but also it is giving results that is beyond 2 decimal places, which will result into failure in my further processing functions.
In [125]: (round(127.650000000000000001,5)//0.05)*0.05
Out[125]: 127.60000000000001
If i execute just the inner round, o/p is 127.65...
In [126]: round(127.650000000000000001,5)
Out[126]: 127.65
But on adding the divide and multiply logic.. the result becomes unexpected.
In [125]: (round(127.650000000000000001,5)//0.05)*0.05
Out[125]: 127.60000000000001
Should there be any datatype issue? or internal precision limitations of python?
how do i overcome it in an elegant way?
PS:
1) I am using python 2.7
2) I am eventually using it in a function. Which is giving unexpected results for this special case. I cannot control the input data quality and its data precision, as it is coming from reading a csv file to dataframe.
def RP(price):# Round down to the nearest price quotable ...i.e. multiple of 0.05
return(round(price//0.05*0.05,2))