So I want to print a float number as an integer. I have a float called "percentage" which should be like percentage=36.1 and I want to print it as an int number, with digits after comma missing.
I use the following code, which is more like using C logic:
percentage=36.1
print "The moisture percentage is at %d %.", percentage
But that gives an error. How would I have to reform it so that it works in Python? What I want to print is: "The moisture percentage is 36%."
percentage=36.1
print "The moisture percentage is at %i%% " %percentage
the string format specification has a percentage already (where 1.0 is 100%):
percentage = 36.1
print("The moisture percentage is at {:.0%}".format(percentage/100))
where the % is the specifier for the percent format and the .0 prevents any digits after the comma to be printed. the %-sign is added automatically.
usually the percentage is just a fraction (without the factor of 100). with percentage = 0.361 in the first place there would be no need to divide by 100.
starting from python >= 3.6 an f-string will also work:
percentage = 36.1
print(f"The moisture percentage is at {percentage/100:.0%}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With