Finding the right format for your data can be tricky. Often you end up printing fixed-point decimal values when what you want are floating-point decimals. Like what you will do if you want to compute tax or income and want to display two decimal places. However, It is not hard to grab two decimal places for your number. Moreover, To print a float to 2 decimal places, you can use the format function.
Working on Jupyter Notebook Anaconda environment Python 3+
Python prints 2 decimal places using the format() command
Invoke format() with “{:.2f}” as str and it will return a string representation of the provided with two decimal places. After formatting the float, call print, it will return it as a string.
power=(2**3.12)
print(power)
two_decimal_place = "{:.2f}".format(power)
print(two_decimal_place)
8.693878900208466
8.69
Write ‘{0:.3g}’.format(number) and you’ll get 2 decimal places. However, The format looks like this:
# a variable having floating-point value
size_boat = 5.4566
# formatted the variable up to 2 decimal place
size_boat = '{0:.3g}'.format(size_boat)
print(size_boat)
5.46
Here is another way of computing the format() function to print 2 decimal places of a number in Python.
format() syntax takes two arguments:
format(value, format_spec='', /)
Where;
Value- the provided variable
Format_spec- is the separator that we want to implement on the variable. Here in the following example; ‘.2f’ is the specifier that format the provided variable and returns 2 decimal place value of the variable.
power=(2**3.12)
print(power)
print(format(power, '.2f'))
8.693878900208466
8.69
Print float number rounded to 2 decimals using f-string
The f-string and string literals approach allows us to print 2 decimal places in Python so Pythonically. The execution procedure is straightforward:
- If the string starts with the prefix letter ‘f’, it becomes an f-string.
- Within commas print the string you want to display on output and end that string with colons (:).
- After that open the curly braces and with curly brackets invoke a variable and end it with a colon (:). Now for 2-decimal formatting use the following syntax:
f'The 2 decimal place number is: {power:.{2}f}'
– using the dot (.) operator open curly braces again and specify the decimal number that you want to print for the provided variable, then close the braces and write prefix f again and end the syntax by closing curly braces and comma.
– and you end up receiving a two-decimal place of the variable.
power=(2**3.12)
print(power)
result = f'The 2 decimal place number is: {power:.{2}f}'
print(result)
8.693878900208466
The 2 decimal place number is: 8.69
Or follows this syntax to print 2 decimal places
f'The 2 decimal place number is: {power:.2f}'
This syntax is similar to the above f-string syntax but here instead of enclosing a decimal place value with curly braces (.{2}f), here skipping those curly braces(.2f), making it more concise and accurate, and flexible.
In this case, however, .2f specifies the format for the floating-point precision function. Two decimal places are precision set here by 2f.
power=(2**3.12)
print(power)
result = f'The 2 decimal place number is: {power:.2f}'
print(result)
8.693878900208466
The 2 decimal place number is: 8.69
The following example has come cautions to be noted that the variables’ height and width should be of one number place (not tens or hundreds (0.00)). In that only case, it returns two decimal places.
size_boat = 5.4566
height = 2
width = 4
print(f'size of boat is: {size_boat:{width}.{height}f}')
size of boat is: 5.46
How to Use the %f Formatter in Python?
%f formatting allows us to print two decimal place values of a number in a more computationally easy way. The procedure is pretty easy:
- Within inverted commas invoke %f formatting and again use the % operator and then a number or variable you want to convert to two decimal places.
- By default %f formatting returns a float number as it is when specifies the decimal value using the (.) operator, it returns the decimal place for that number and represents the number as a string.
size_boat = 5.4566
print("%.1f" % size_boat) #print one decimal place
print("%.2f" % size_boat) #print 2 decimal place
5.5
5.46
Use a list comprehension to print two decimal places
Using the list comprehension method to print the two decimal places for every value within a provided list. Using for…in structure in aggregation with f-string depression to print two decimal places.
The procedure goes like this:
The for…in structure iterate every element in the list_of_size_boat over an f-string expression. Every element iterates and is converted to 2 decimal places using f-string formatting until and unless the last element iteration completes.
list_of_size_boat = [200.50505, 300.5555, 5.5]
boat_size = [f'{i:.2f}' for i in list_of_size_boat]
print(boat_size)
['200.51', '300.56', '5.50']
It will return every dimension of the boat to two decimal places and returns a list of each dimension.
Using a round() in aggregation with a list comprehension structure
The round() function is a built-in function that allows to representation of two decimal places of the float number. However, using list comprehension structure in aggregation with round() functions helps us to convert and print every float number in a list to two decimal places in Python.
However, a round takes two arguments;
round(variable, decimal places)
Where;
Variable– variable is the number
Decimal places– decimal places that are desired to be displayed as output.
list_of_size_boat = [200.50505, 300.5555, 5.5]
two_decimal_place_dim = [round(list_of_size_boat, 2) for list_of_size_boat in list_of_size_boat]
print("Original List:", list_of_size_boat)
print("Rounded List:", two_decimal_place_dim)
Original List: [200.50505, 300.5555, 5.5]
Rounded List: [200.51, 300.56, 5.5]
Using %f formatting with list comprehension structure
The %f formatting in Python gives the flexibility to print two decimal places in Python. However, here in this case using %f formatting with list comprehension structure to convert every element in the list to two decimal places using for loop iteration procedure.
list_of_size_boat = [200.50505, 300.5555, 5.5, -11.111]
two_decimal_place_dim = ['%.2f' % i for i in list_of_size_boat]
print("list_of_size_boat List:", list_of_size_boat)
print("two_decimal_place_dimension List:", two_decimal_place_dim)
list_of_size_boat List: [200.50505, 300.5555, 5.5, -11.111]
two_decimal_place_dimension List: ['200.51', '300.56', '5.50', '-11.11']
Using ceil() function
ceil() built-in function in Python provides flexibility to print two decimal places of the float number Pythonically. However, here is how it executes:
- Import math module for computation
- Define a variable of a float type
- Invoke math module with ceil() function using dot (.) operator to compute and print two decimal places of the provided number.
# importing the math module for computation
import math
# a variable having floating-point value
size_boat = 5.4566
# round off the variable using ceil() function upto 2 decimal place
print("2 decimal places: ")
new_dimension = math.ceil(size_boat*100)/100
print(new_dimension)
2 decimal places:
5.46
Using the round() function to display two-decimal places and round the numbers
A rounding number requires two arguments: the number to round and the number of decimal places to return. The syntax follows:
round(number, ndigits=None)
Here it returned two decimal places.
# a variable having floating-point value
size_boat = 5.4566
# round off the variable up to 2 decimal place
round(size_boat, 2)
5.46
Using Decimal’s initializer
A slash cannot be entered into Decimal’s initializer. As a rule of thumb, Decimal’s initializer returns output as the string appears as a single number.
You can use Decimals as follows:
getcontext().prec = 2
Decides the decimal places you want to print.
from decimal import *
getcontext().prec = 2
Decimal(1) / Decimal(6)
Decimal('0.17')
Lambda function to format up to two decimal places
However, use a lambda expression like this to print two decimal places of the specific number.
- Be cautious about using slashes to compute one expression using the lambda function.
x = lambda x,i : x*(10**i)//1/(10**i)
x(5.6789, 2)
5.67
Use NumPy to print two decimal places
Whenever you need to round a number to a resolution, the following method can be used:
- Setting 0.01 to achieve two decimals places
- Handling NumPy with round() function using dot (.) operator to print two decimal places.
import numpy as np
# a variable having floating-point value
size_boat = 5.4566
# formatted the variable up to 2 decimal place
resolution = 0.01
two_decimal_place= int(np.round(size_boat/resolution))*resolution
print(two_decimal_place)
5.46
An additional way in Python to print 2 decimal places
Using %F with round() function to print two decimal places.
# a variable having floating-point value
size_boat = 5.4566
print("%.2f" % round(size_boat, 2))
5.46
Using format() expression with round() function to print two decimal places.
# a variable having floating-point value
size_boat = 5.4566
print("{:.2f}".format(round(size_boat, 2)))
5.46
Setting 100 resolution to print two decimal places and sum up with 0.5 to round the number.
# a variable having floating-point value
size_boat = 5.4566
size= int((size_boat * 100)) / 100.0
print(size)
#now round off the value by adding 0.5
size= int((size_boat * 100)+0.5) / 100.0
print('round up:', size)
5.45
round up: 5.46
Better approach {:.2f} vs {0:.2f}
{:.2f} vs {0:.2f}, both help to represent the number up to two decimal places. However, format takes multiple arguments, and we can specify both argument index within curly braces {}, {0:.2f} specify the index location for the argument passed to the format() function.
# a variable having floating-point value
size_boat = 5.4566
#instead of this
print("{:.2f}".format(size_boat))
#use this
print("{0:.2f}".format(size_boat))
5.46
5.46
Conclusion
This tutorial demonstrates how to print two decimal places in Python. The page covers various methods with example code to print two decimal places. However, use the one that fits your problem.
If you want to learn more about Python Programming, visit Python Programming Tutorials.