3

I am trying to finish an assignment and am very close by python is always rounding my answer down instead of up when it's supposed to. Here is my code:

startingValue = int(input())
RATE = float(input()) /100
TARGET = int(input())
currentValue = startingValue
years = 1

print("Year 0:",'$%s'%(str(int(startingValue)).strip() ))

while years <= TARGET :
  interest = currentValue * RATE
  currentValue += interest
  print ("Year %s:"%(str(years)),'$%s'%(str(int(currentValue)).strip()))
  years += 1

Here is what my code outputs: Year 0: $10000, Year 1: $10500, Year 2: $11025, Year 3: $11576, Year 4: $12155, Year 5: $12762, Year 6: $13400, Year 7: $14071, Year 8: $14774, Year 9: $15513,

Here is what is supposed to output: Year 0: $10000, Year 1: $10500, Year 2: $11025, Year 3: $11576, Year 4: $12155, Year 5: $12763, Year 6: $13401, Year 7: $14071, Year 8: $14775, Year 9: $15514,

I need them to match, AKA round up. Someone please help me :(

MollyV
  • 55
  • 2
  • 3

2 Answers2

5

In Python the int() constuctor will always round down, eg

>>> int(1.7)
1

https://docs.python.org/2/library/functions.html#int

If x is floating point, the conversion truncates towards zero.

If you want to always round up, you need to:

>>> import math
>>> int(math.ceil(1.7))
2

or rounded to nearest:

>>> int(round(1.7))
2
>>> int(round(1.3))
1

(see https://docs.python.org/2/library/functions.html#round ...this builtin returns a float)

Anentropic
  • 32,188
  • 12
  • 99
  • 147
0

Casting to an int always truncates; imagine it chopping off all the decimal points.

Use round() to round to the nearest integer.

Athena
  • 3,200
  • 3
  • 27
  • 35