close

How to print a float variable using the % formatting?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to print a float variable using the % formatting in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to print a float variable using the % formatting?

  1. How to print a float variable using the % formatting?

    If you want to use the variable's string representation, you can also always just use %s. But since you are on python 3.7, there are some more modern approaches as well.

  2. print a float variable using the % formatting

    If you want to use the variable's string representation, you can also always just use %s. But since you are on python 3.7, there are some more modern approaches as well.

Method 1

As you try print float number, use %f instead of %d. This code will print the number to 4 decimal places:

result_2 = 4.523529411764706
statement_2a = "Your text contains an average length of %.4f letter(s) per words." % result_2

print(result_2)
print(statement_2a)

Method 2

You are using “old-style” formatting and used %d as the placeholder. This will represent your number as a decimal number without any fractions. If you want to display floating point numbers, the placeholder is simply %f.

If you want to use the variable’s string representation, you can also always just use %s. But since you are on python 3.7, there are some more modern approaches as well.

  • “old-style” formatting: "%s" % var
  • “new-style” formatting using format()"{}".format(var) (Read up on python formatters for details)
  • f-strings, which are basically syntactic sugar for format()-based string interpolation. You prefix with f and put the variables in the string literal itself: f"{var}"

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read