简体   繁体   中英

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 .

Eg 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?

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

IIUC, try:

import math
def nearest(n):
    if n%10 > 4:
        return math.ceil(n/10)*10 - 1
    return math.floor(n/10)*10 - 1

>>> nearest(734)
729

>>> nearest(734.1)
739

>>> nearest(733.9)
729

You could get the integer division by 10 with a condition on the remainder, and multiply by ten to get the nearest 10, then subtract 1:

def nearest9(n):
    d,r = divmod(n,10)
    return int(d+(r>4))*10-1

>>> nearest9(734.1)
739

>>> nearest9(734)
729

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM