-1

My returned average does not look right in terms of decimal places using +str for a variable.

my code below should provide 25.83 but I get 25.830000000002

total_bmi = 0

for bmi in bmis:
  total_bmi += float(bmi)

average_bmi = total_bmi/len(bmis)
print("Average BMI: " + str(average_bmi))
Sal
  • 1
  • 1
    When I got here, there were 5 upvotes on the automatically generated comment proposing a duplicate question. If you think something is a duplicate, and you have the reputation required to cast close votes, please **actually vote to close** duplicates, don't just upvote the "does this answer your question?" comment. Especially if it's a common problem, like here. – Karl Knechtel Jan 05 '23 at 04:00

1 Answers1

-1

The reason for this is how floating point numbers are stored in hardware. Without going into much detail, simply use:

total_bmi = 0

for bmi in bmis:
  total_bmi += float(bmi)

average_bmi = total_bmi/len(bmis)
print("Average BMI: " + str(round(average_bmi, 2)))
Michael Ruth
  • 2,938
  • 1
  • 20
  • 27
madhurkant
  • 96
  • 9
  • 1
    Don't use `round` for this; use string formatting. That's what it's for. `print(f"Average BMI: {average_bmi:.2f}")`. Or `print("Average BMI: {:.2f}".format(average_bmi))`. – Mark Dickinson Jan 05 '23 at 11:23