1

I'm trying to round some floats in a df to 2 dp but all multiples of 10 are rounded to 1 dp, so 3.60 would be 3.6 and 12.40 would be 12.4...

I have a df:

Values           A         B         C         D
Question                                                                                                    
A2         4.08642  4.144279  3.601626  3.983852

my code

np.round(df,2)

output

Values        A     B    C     D
Question                                                                                                    
A2         4.09  4.14  3.6  3.98

expected output

Values        A     B     C     D
Question                                                                                                    
A2         4.09  4.14  3.60  3.98

how can I force np.round to display '3.6' as '3.60'?

FYI - I don't want to use a string formatter because I have to round these numbers.

Boosted_d16
  • 13,340
  • 35
  • 98
  • 158
  • 1
    "I don't want to use a string formatter because I have to round these numbers" - how are those two things in any way related? Why would having to round the numbers make you not want to use string formatting? – user2357112 Apr 14 '15 at 09:27

3 Answers3

4

The problem is not with the rounding, but with the way pandas displays the DataFrame.

You can set float_format like:

pd.options.display.float_format = '${:,.2f}'.format

As explained in more details in this answer.

Community
  • 1
  • 1
shx2
  • 61,779
  • 13
  • 130
  • 153
1

You can use string formater and then use Decimal function form library decimal to return number again:

Example code:

import decimal
print(decimal.Decimal("{:.2f}".format(3.6)))
Julia K
  • 46
  • 7
1

Another way to set the pandas display.float_format option:

>>> pd.set_option('float_format', '{:,.2f}'.format)
Vidhya G
  • 2,250
  • 1
  • 25
  • 28