Skip to content
Advertisement

Round last digit integer to nearest 9

Set-up

I have a set of prices with decimals I want to end on the nearest 9, where the cut-off point is 4.

E.g. 734 should be 729, 734.1 should be 739 and 733.9 should be 729.

Prices can be single, double, triple, and quadruple digits with decimals.


Try

if int(str(int(757.2))[-1]) > 4:
    p = int(str(int(757.2))[:-1] + '9')

Now, this returns input price 757.2 as 759, as desired. However, if the input price would be ending on a 3 and/or wouldn’t be a triple-digit I wouldn’t know how to account for it.

Also, this approach seems rather cumbersome.

Is there someone who knows how to fix this neatly?

Advertisement

Answer

Just do the typical round to 10 and shift by 1 before and after:

def round9(n):
    return round((n+1) / 10) * 10 - 1

round9(737.2)
# 739
round9(733.2)
# 729
round9(734.0)
# 739
round9(733.9)
# 729
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement