String formatting python floats

How to print a float variable using the % formatting?

I’m using Python 3.7.1 on Windows. When I print a float variable using the % formatting. only the natural part is printed. Here is an example:

result_2 = 4.523529411764706 statement_2a = "Your text contains an average length of %d letter(s) per words." % result_2 print(result_2) print(statement_2a) 
4.523529411764706 Your text contains an average length of 4 letter(s) per words. 
Your text contains an average length of 4.5235 letter(s) per words. 
  1. How do I prevent the print() function from practically deleting the decimal numbers?
  2. How to round the number to four decimal digits

4 Answers 4

There are several options to evaluate expressions and print them as a string in python.

There are already some good answers, but here are some explicit examples and links to the documentation.

Formatted string literals (f-strings)

f-strings allow you to input expressions which are evaluated at run-time. In the f strings expressions are encased by curly brackets.

x = 42.222222222 print(f'My value is: ') 

prints My value is: 42.222222222 .

and with specifying the format:

x = 42.222222222 print(f'My value is: ') 

Str formatting method

Strings have a built-in .format() method where you can specify replacement fields with curly brackets.

x = 42.222222222 print('My value is: <>'.format(x)) 

prints My value is: 42.222222222 .

and with string formatting:

x = 42.222222222 print('My value is: '.format(x)) 

String formatting operator

x = 42.222222222 print('My value is: %' % x) 

prints My value is: 42.222222222 .

and with string formatting:

x = 42.222222222 print('My value is: %.2f' % x) 

See @Felk answer for some more qualitive descriptions of the different methods.

Читайте также:  Read part file python

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) 

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»»

A better alternative than % formatting would be to use .format .

result_2 = 4.523529411764706 print(result_2) print("Your text contains an average length of <> letter(s) per words.".format(result_2)) 
result_2 = 4.523529411764706 print(result_2) print("Your text contains an average length of <> letter(s) per words.".format(round(result_2,4))) 

But if you feel comfortable with % formatting then to print whole number use %s

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

For rounding to 4 digits use %1.4f

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

Источник

How to format a floating number to fixed width in Python

The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:

  • The empty string before the colon means «take the next provided argument to format() » – in this case the x as the only argument.
  • The 10.4f part after the colon is the format specification.
  • The f denotes fixed-point notation.
  • The 10 is the total width of the field being printed, lefted-padded by spaces.
  • The 4 is the number of digits after the decimal point.
Читайте также:  Php pass by reference string

So I understand that the 4f represents limiting the decimals to 4 (with trailing zeros), but what does the 10 mean? Does that mean this formatting won’t work with integers greater than 9999999999 (ten 9’s)? Just curious.

@hobbes3: 10 is the minimum field width, i.e. the minimum length of the printed string. Numbers are by default right-aligned and padded with spaces — see the documentation for more details.

It has been a few years since this was answered, but as of Python 3.6 (PEP498) you could use the new f-strings :

numbers = [23.23, 0.123334987, 1, 4.223, 9887.2] for number in numbers: print(f'') 
 23.2300 0.1233 1.0000 4.2230 9887.2000 

Note that the width also includes dot character. So if you specify 9 to be width, 1 will be used for printing the dot, the other 8 will be for printing digits and spaces.

In python3 the following works:

>>> v=10.4 >>> print('% 6.2f' % v) 10.40 >>> print('% 12.1f' % v) 10.4 >>> print('%012.1f' % v) 0000000010.4 

This has changed in the last 4 years, now % formatting is the oldest method of formatting. For several reasons using str.format or f-strings is preferred over % . Previously when it was only str.format , people had some reasons but f-strings fixed that hole. format mini-language docs, str.format examples from docs and f-string literals examples in docs

You can also left pad with zeros. For example if you want number to have 9 characters length, left padded with zeros use:

Thus, if number = 4.656 , the output is: 00004.656

For your example the output will look like this:

numbers = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000] for x in numbers: print(''.format(x)) 
00023.2300 00000.1233 00001.0000 00004.2230 09887.2000 

One example where this may be useful is when you want to properly list filenames in alphabetical order. I noticed in some linux systems, the number is: 1,10,11. 2,20,21.

Читайте также:  Простая анимация css примеры

Thus if you want to enforce the necessary numeric order in filenames, you need to left pad with the appropriate number of zeros.

Источник

Оцените статью