0

I have a code that currently looks like this, to take user input and to return to cents. Now I want to modify my code, so it can round to the nearest 5, what kind of changes should I made? Current code:



The example new input and output are:

input = 1.34, output =1.35

input =3.46, output =3.45

input = 123.42, output =123.40

input =123.43, output = 123.45

input 123.47, output =123.45

input 123.48, output = 123.50

OMG C
  • 97
  • 5

2 Answers2

1

One way to implement that rounding would be:

rounded_cents = round(cents / 5) * 5

However, since the Python round() function behaves somewhat oddly when given values of 0.5, you might replace round() with:

floor(input_number + 0.5)

Making the final line of code:

rounded_cents = floor(cents / 5 + 0.5) * 5

Lyndon Gingerich
  • 604
  • 7
  • 17
0

might not be efficient, but I think this does the task

def myround(x, base=5):
  rem = int(str(x)[-2:])
  stem = int(str(x)[0:-3])

  #print('rem is ',rem)
  #print('stem is ',stem)  
  sol = base * round(rem/base)
  return float(str(stem)+'.'+str(sol))
  
cents = 1.48
new_cents = myround(cents)
print(new_cents)

UPDATE1: similar to your function

def adjust(cents,base = 5):
    rem = int(str(cents)[-2:])
    stem = int(str(cents)[0:-3])
    #print('rem is ',rem)
    #print('stem is ',stem)  
    converted = base * round(rem/base)
    return float(str(stem)+'.'+str(converted))
  
cents =(input("Enter a number of cents between 0 and 9: "))
# new instruction for user
#cents =(input("Enter a number with decimal place: "))
# and I will need to change this to float

print("The final round of number is: " + str(adjust(cents)))

Explanation :

You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do exactly that (round(float(x)/5) where float is only needed in Python2), and then since we divided by 5, we multiply by 5 as well. The final conversion to int is because round() returns a floating-point value in Python 2.

I made the function more generic by giving it a base parameter, defaulting to 5.

This is a tweaked version of this answer...

SANGEETH SUBRAMONIAM
  • 1,098
  • 1
  • 9
  • 10