0

How to round 6.25 to 6.3 and 6.24 to 6.2 in Python?

The 'round' function is rounding 6.25 to 6.2:

mynum = 6.25
print(round(mynum, 1))

produces 6.2 and I really need it to produce 6.3 It seems to only round up with 6 like 6.26 produces 6.3

Just to be clear: I want 6.25 to round to 6.3 and 6.24 to round to 6.2

Mattman85208
  • 1,858
  • 2
  • 29
  • 51
  • 2
    Also related: [Is floating point math broken?](https://stackoverflow.com/q/588004/11082165) – Brian61354270 Dec 20 '22 at 18:13
  • 1
    Rounding with 5 is cultural dependant and somehow ill defined. There is no correct way to do it, just several different conventions. Could you define the expected output of the rounding function? – jlandercy Dec 20 '22 at 18:15
  • 1
    Python 3 default is to use "banker's rounding"... https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior – JonSG Dec 20 '22 at 18:19
  • 1
    @Brian Not really. `6.25` can, in fact, be represented exactly. It's the rounding algorithm used, not any imprecision in the value, that maps 6.25 to 6.2. – chepner Dec 20 '22 at 18:30
  • This works: import decimal newmynum = decimal.Decimal(6.25).quantize(decimal.Decimal('1.0'), rounding=decimal.ROUND_HALF_UP) print(newmynum) – Mattman85208 Dec 20 '22 at 18:46

0 Answers0