rahul891
rahul891

Reputation: 89

pandas.DataFrame.round() not truncating decimal values after desired number of places

pandas.DataFrame.round() gives somewhat unpredictable output on the below data frame. Can anyone please help me understand what is happening here?

df = pd.DataFrame([(61.21, 69.32), (65.1938, .67)], columns=['A', 'B'], dtype='float32')
df.round(2)

The above code outputs:

           A      B
0  61.209999  69.32
1  65.190002   0.67

Why does round(2) not truncate all but first 2 digits after decimal point? When I try the same with dtype='float64' it works and outputs below:

df.astype('float64').round(2) 
       A      B
0  61.21  69.32
1  65.19   0.67

Is there something about the values in the data frame?

I don't want to format the output as string (round(2).applymap('{:.2f}'.format)) to get the desired number of decimals. I want to know why the columns are giving different number of digits after the decimal point.

I am using pandas version '0.24.1'.

Upvotes: 4

Views: 7360

Answers (1)

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 2914

Floating points are not precise, not every number can be represented exactly. The same way 1/3 can't be represented precisely with a finite decimal number, there are many numbers which can't represented exactly in an IEEE floating point format (which might be however representable in a decimal system).

In such a case, floating point operations, including rounding (to decimal places), will return a value depending on the chosen rounding mode, usually the nearest floating point number.

This number might be just slightly less than the actual decimal value with two decimal places, thus having alot of nines in decimal notation.

Upvotes: 1

Related Questions