Printing float number as integer in Python

11,997

Solution 1

percentage=36.1
print "The moisture  percentage is at %i%% " %percentage

Solution 2

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%}")

Solution 3

You can see the different formatting options in the python docs.

print "The moisture  percentage is at {0:.0f} %.".format(percentage)

Solution 4

percentage=36.1
print "The moisture  percentage is at %d %s"%(percentage,'%')
Share:
11,997

Related videos on Youtube

Tasoulis Livas
Author by

Tasoulis Livas

Updated on September 16, 2022

Comments

  • Tasoulis Livas
    Tasoulis Livas over 1 year

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

    • Barmar
      Barmar almost 7 years
      int(percentage)