[Tutor] Python problem

Mats Wichmann mats at wichmann.us
Sat Feb 20 12:06:29 EST 2021


On 2/20/21 4:27 AM, Vakhtang Kvaratskhelia wrote:
> Hello,
> 

> 0% to 100%. Your code should print out a decimal (e.g. 0.0704 for 7.04%)."
> but i am not able to.

> this is the code i have written and it gives the correct amount as a
> solution except it is not rounded to 4 decimals

A floating point number is just a representation, it's not intrinsically 
rounded.  You do know that you can control the formatting of what you 
print? Or is that something that hasn't been taught yet (this is from a 
course, right)?

> print("Optimal portion saved is = ",portion_saved)

For example, you can do this (one of several different ways to control 
the conversion of the float to the string that will be printed):

print(f"Optimal portion saved is {portion_saved:.4f}")

(Python's "f-strings" are comparatively new, and don't work on Python 
versions prior to 3.6)

Alternatively, Python has a decimal floating point library that is 
intended for this kind of usage:

https://docs.python.org/3/library/decimal.html



More information about the Tutor mailing list