I have some prices like 5.35, 10.91, 15.55, which I round with two decimals using
Price = "{:.2f}".format(Price)
But how can I make them to be round based on fixed decimals 0.50 and 0.90 and have
5.50, 10.90, 15.50
Thank you
I have some prices like 5.35, 10.91, 15.55, which I round with two decimals using
Price = "{:.2f}".format(Price)
But how can I make them to be round based on fixed decimals 0.50 and 0.90 and have
5.50, 10.90, 15.50
Thank you
This function should do the trick for the examples that you provided:
def fixed_round(number):
decimal = number - int(number)
if (abs(0.5 - decimal)) < (abs(0.9 - decimal)):
return int(number) + 0.50
else:
return int(number) + 0.90
If you want it to round to full numbers, in the case where the decimals are closer to the integer than to 0.5, you will need to adjust for that ;)
If you have float number with the fractional part you can use first and second example else with all number (in fact all other type) you can use third and fourth. Num is your fractional part. x is yout 0.5 and y your 0.9
def round(num, x, y) :
av = (x+y)/2
if num < av :
return x
return y
Or if you want pass numer like 15.98:
def round(num, x, y) :
av = (x+y)/2
if num % 1 < av :
return int(num)+x
return int(num)+y
You can than call:
round(15.98,0.5,0.9)
Output: 15.9
Or something like:
def round(number):
x=0.5
y=0.9
if type(number) is float:
av = (x+y)/2
if number % 1 < av :
return int(number)+x
return int(number)+y
return number
All of this is rounding down. If you would like round up the construction will be:
def round(number):
x=0.5
y=0.9
if type(number) is float:
av = (x+y)/2
from builtins import round as rd
if rd(number % 1,2 ) < av :
return int (number)+x
return int (number)+y
return number
import math
def weird_round(x):
if round(x % 1, 1) >= 0.9:
return math.floor(x) + 0.9
return math.floor(x) + 0.5
prices = [5.35, 10.91, 15.55]
for price in prices:
text = "{:.2f}".format(weird_round(price))
print(price, '->', text)
5.35 -> 5.50
10.91 -> 10.90
15.55 -> 15.50