0

before OP takes down my question, please note that I have viewed posts: pandas python - round() not behaving correctly

round() doesn't seem to be rounding properly

and they don't answer my question.

My question is similar on those, as you may have known that python does not round half values correctly (in a standard way), i.e.:

2.5 -> 2

2.25 -> 2.2

whereas we know that:

2.5 should be ->3

2.25 should be -> 2.3 etc...

now I have a Pandas Series object say below:

index Another header
1 2.25
2 3.55
3 4.44
4 5.56
5 6.23
6 7.45

I currently have the code Series.apply(lambda x: round(x, 1))

and have created this function:

def correctRound(x: float, n: int):

    target_precision = "1." + "0" * n
    rounded_x = float(Decimal(x).quantize(Decimal(target_precision), dwRound))
    if n == 0:
        rounded_x = int(rounded_x)
    return rounded_x

however this could not be worked on Series, how could I correctly round a DataFrame or Series object?

Thanks a lot for the help

Dazz W
  • 113
  • 8
  • also look this [Python 3.x rounding behavior](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) – Anurag Dabas Jun 03 '21 at 16:27
  • 1
    _python does not round half values correctly,_ -- This statement is incorrect. You apparently believe there is only one accepted rounding method. That's wrong. Python implements "banker's rounding" which rounds x.5 to the nearest even integer. 2.25 becomes 2.2, but 2.35 becomes 2.4. It is quite correct, even if it is not the rounding you wanted. – Tim Roberts Jun 03 '21 at 17:32

1 Answers1

0

I realised that I have made this more complicated than it seems, I have just done a little trick, all I had to do was just to add 0.00000001 say into the number and the rounding can be done in the normal way.

round(2.25+0.000001, 1) -> 2.3
Dazz W
  • 113
  • 8