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?
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
You could get the integer division by 10 and multiply by ten to get the nearest 10, then subtract 1:
def nearest9(n):
return int(n//10)*10-1
>>> nearest9(734.1)
729
>>> nearest9(733.9)
729