0

There is a piece of code that is giving me trouble

i have the variable Average = 94.56 and and another arbitrary variable student

I am asked to print this variable but in the string i must format it such that instead of 94.56 i get 94.6 when i call the print function so this is what i have

print(Student + " " + 'class average was' + " " + str(Average + .04))

but i get this ugly number

  • Elsa Martinez class average was 94.60000000000001

Why does it do this and how can i just get 94.6

thanks

tripleee
  • 175,061
  • 34
  • 275
  • 318

2 Answers2

1

What you want to do is rounding.

print(Student + " " + 'class average was' + " " + str(round(Average,1)))

round(number, digits) method takes two argument, number which is a float that you want to round, digits is the number of digits after decimal place you want to round to, in your case 1 digit

justgoodin
  • 301
  • 1
  • 11
0

The reason that you get a number slightly higher than the real answer is because of the way most coding languages add floating numbers.

Using the round() method will solve your issue in this case.

Dimo
  • 26
  • 3