Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I have been utilizing the code underneath to conveniently adjust to 1dp where I required the .5s to adjust upwards, for example, I needed a value, for example, 36.25 to adjust to 36.3, not 36.2. 

def my_round(n, ndigits=1):

    try:

       part = n * 10 ** ndigits

       delta = part - int(part)

       # always round "away from 0"

       if delta >= 0.5 or -0.5 < delta <= 0:

           part = math.ceil(part)

       else:

           part = math.floor(part)

       val =  part/(10 ** ndigits)

    except ValueError:

       val = np.nan

    return val

I currently need to round an alternate decimal column in a df to the closest 5 whole numbers. Would anyone be able to help recommend how I can change my unique code above? I need, for instance, a worth, for example, 702.5000 adjusting to 705. Utilizing the normal Round() it clearly goes to 700. In the model, any remaining ordinary adjusting rules ought to apply for example

702.222 to 700,

707.466 to 705,

703.021 to 705

1 Answer

0 votes
by (26.4k points)

You can use the below function, if you want to round to a certain number:

def my_round(x: float, round_to: float = 5, dp: int = 0) -> float: 

    round_to *= 10**dp 

    x *= 10**dp 

    return ((x + round_to / 2) // round_to * round_to) / 10**dp 

Testing it,

values = [702.500, 702.222, 707.466, 703.021]

targets = [705., 700., 705., 705.]

assert [my_round(x, 5, 0) for x in values] == targets

assert my_round(3.25, 0.1, 1) == 36.3

Are you pretty much interested to learn python in detail? Come and join the python training course to gain more knowledge.

 

Related questions

Browse Categories

...