'Allowing user to input how many decimals wanted, calculate percentage
numerator = int(input("Please enter the numerator: "))
denominator = int(input("Please enter the denominator: "))
decimal = int(input("Please enter the number of decimal places: "))
percent = numerator/denominator
format_string = "{:.2f}".format(percent)
I changed the .2
in the format_string to decimal as in {:.decimalf}
to allow the user to decide how many decimal places. Python does not allow me to use a variable for this for some reason.
Solution 1:[1]
You can do it like this:
format_string = "{:.{decimal}f}".format(percent, decimal=decimal)
or even:
format_string = "{:.{}f}".format(percent, decimal)
Solution 2:[2]
You can escape braces in format string by doubling them
decimal_places = 4
format_string = "{{:.{}f}}".format(decimal_places) # '{:.4f}'
format_string.format(1/2) # '0.5000'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lukasz Wiecek |
Solution 2 | Iain Shelvington |