2

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

1
  • 1
    int(percentage) Commented May 25, 2017 at 9:05

5 Answers 5

5
percentage=36.1
print "The moisture  percentage is at %i%% " %percentage
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

3

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

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

Comments

2
percentage=36.1
print "The moisture  percentage is at %d %s"%(percentage,'%')

Comments

0

In python3.x

percentage=36.1
print("The moisture percentage is at "+str(int(percentage))+"%")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.