3

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

  • Do you want every number to have the decimals rounded to the closest value between .50 and .90? So .35 becomes .50 and .82 becomes .90? – Luca Bezerra Apr 10 '19 at 12:12
  • Yes that is correct –  Apr 10 '19 at 12:14
  • 1
    You need some custom rounding function as this 0.5, 0.9 is not standard. – smido Apr 10 '19 at 12:15
  • 1
    Possible duplicate of [Limiting floats to two decimal points](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – Ashish Apr 10 '19 at 12:25

3 Answers3

0

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 ;)

Jones1220
  • 786
  • 2
  • 11
  • 22
0

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
ElConrado
  • 1,477
  • 4
  • 20
  • 46
-1
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
ramazan polat
  • 7,111
  • 1
  • 48
  • 76