Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing float number as integer in Python

Tags:

python

int

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%."

like image 495
Tasoulis Livas Avatar asked Jun 19 '26 05:06

Tasoulis Livas


2 Answers

percentage=36.1
print "The moisture  percentage is at %i%% " %percentage
like image 184
Numlet Avatar answered Jun 20 '26 19:06

Numlet


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%}")
like image 31
hiro protagonist Avatar answered Jun 20 '26 19:06

hiro protagonist