0

I have imported cs50 module and am using cs50.get_float to store user input for greedy.py. I am having trouble with the floats to ints in Python. In C, we converted the float in cents by multiplying by 100 and then rounding using the round() function.

I know there is no comparable function in Python to round(), but I can't even multiply the float by 100 and not get rounding errors. I know why this occurs, I just don't know where to go from here.

Searching the web, I have seen tons of discussions about input() as a string and so forth, using complex ways to convert to int from float, etc. There has to be an easier way!

Anywhere I can find the answer in the Python documentation?

1

In this situation, the easy way is to use int(). There is also a function called round() which you could use instead.

5
  • Round() truncates the decimal portion of the float and int() reveals the imprecision memory storage, so neither works. – Flesheaters Feb 9 '17 at 18:18
  • I'm not sure I follow. You say in the original question that "In C, we converted the float in cents by multiplying by 100 and then rounding using the round() function." Why does the same approach not work with Python's round()? – Levi Roth Feb 10 '17 at 0:00
  • I just figured it out! You have to use the round function inside of the int function to get it to work! – Flesheaters Feb 10 '17 at 1:03
  • I don't see how int(round(x)) would give a different result to just round(x). round() returns an integer if you don't specify a number of decimal places anyway, so casting it to an integer would make no difference. – Steve Bunting Feb 10 '17 at 21:21
  • I believe what's happening is that round is rounding the value up in some cases, so for this problem the poster wants 45/25 to return 1, but round is returning 2. They don't actually need to run int(round(45/25)) to achieve this, you can just run int(45/25). – Sean May 28 '20 at 17:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .