Fixed Digits After Decimal with F-Strings

Fixed digits after decimal with f-strings

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

Rounding float using f-string

Include the type specifier in your format expression

format specifier:

f'{value:{width}.{precision}}'

example:

# Formatted string literals
x = 3.14159265
print(f'pi = {x:.2f}')

Format variable in f-string with a variable number of decimal places

This should work:

n = 5
value = 0.345
print(f'{value:.{n}f}')

Output:

0.34500

Convert float to Decimal with fixed digits after decimal

Do all the formatting on the way out from your code, inside the print and write statements. There is no reason I can think of to lose precision (and convert the numbers to some fixed format) while doing numeric calculations inside the code.

Python f-string with a Variable Decimal Number Specifier

You put a second set of brackets inside the first one:

number = 2
print(f'{1.23456:.{number}f}')
# 1.23

How to format a floating number to fixed width in Python

numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]                                                                                                                                                   

for x in numbers:
print("{:10.4f}".format(x))

prints

   23.2300
0.1233
1.0000
4.2230
9887.2000

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.

How to display two decimal points in python, when a number is perfectly divisible?

The division works and returns adequate precision in result.

So your problem is just about visualization or exactly:

  • string-representation of floating-point numbers

Formatting a decimal

You can use string-formatting for that.
For example in Python 3, use f-strings:

twoFractionDigits = f"{result:.2f}"

or print(f"{result:.2f}")

The trick does .2f, a string formatting literal or format specifier that represents a floating-point number (f) with two fractional digits after decimal-point (.2).

See also:

  • Fixed digits after decimal with f-strings
  • How to format a floating number to fixed width in Python

Try on the Python-shell:

Python 3.6.9 (default, Dec  8 2021, 21:08:43) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> a=1.175 #value of a after some division
>>> result = math.floor(a*100)/100
>>> result
1.17
>>> print(result)
1.17
>>> a=25/5 #Now a is perfectly divisible
>>> result = math.floor(a*100)/100
>>> result
5.0
>>> print(result)
5.0
>>> print(f"{result:.2f}")
5.00

Formatting a decimal as percentage

Similar you can represent the ratio as percentage:
print(f"{result:.2f} %")

prints:

5.00 %

A formatting shortcut for percentage can be:
print(f"{25/100:.2%}")
Which converts the result of 25/100 == 0.25 to:

25.00%

Note: The formatting-literal .2% automatically converts from ratio to percentage with 2 digits after the decimal-point and adds the percent-symbol.

Formatting a decimal with specific scale (rounded or truncated ?)

Now the part without rounding-off, just truncation.
As example we can use the repeating decimal, e.g. 1/6 which needs to be either rounded or truncated (cut-off) after a fixed number of fractional digits - the scale (in contrast to precision).

>>> print(f"{1/6:.2}")
0.17
>>> print(f"{1/6:.2%}")
16.67%

Note how the formatted string is not truncated (to 0.16) but rounded (to 0.17). Here the scale was specified inside formatting-literal as 2 (after the dot).

See also:

  • Truncate to three decimals in Python
  • How do I interpret precision and scale of a number in a database?
  • What is the difference between precision and scale?

Formatting many decimals in fixed width (leading spaces)

Another example is to print multiple decimals, like in a column as right-aligned, so you can easily compare them.

Then use string-formatting literal 6.2f to add leading spaces (here a fixed-width of 6):

>>> print(f"{result:6.2f}")
5.00
>>> print(f"{100/25*100:6.2f}")
400.00
>>> print(f"{25/100*100:6.2f}")
25.00

See also

All the formatting-literals demonstrated here can also be applied using

  • old-style %-formatting (also known as "Modulo string formatting") which was inherited from printf method of C language. Benefit: This way is also compatible with Python before 3.6).
  • new-style .format method on strings (introduced with Python 3)

See theherk's answer which demonstrates those alternatives.

Learn more about string-formatting in Python:

  • Real Python: Python 3's f-Strings: An Improved String Formatting Syntax (Guide)
  • Real Python: Python String Formatting Best Practices

Rounding floats with f-string

How about this

x = 3.14159265
print(f'pi = {x:.2f}')

Docs for f-strings



Related Topics



Leave a reply



Submit