Python floating point precision

Python print 2 decimal places [%.2f in Python]

In this Python tutorial, we will discuss on how to print 2 decimal places in Python.

  • Python print 2 decimal places
  • Python float precision truncate
  • Python float precision ceil
  • Python float precision floor
  • Python decimal format
  • Python round numbers
  • Limiting floats to two decimal points

Python print 2 decimal places

In Python, to print 2 decimal places we will use str.format() with “” as string and float as a number. Call print and it will print the float with 2 decimal places.

float = 2.154327 format_float = "".format(float) print(format_float)

After writing the above code (python print 2 decimal places), Ones you will print “ format_float ” then the output will appear as a “ 2.15 ”. Here, it will format the float with 2 decimal places.

You can refer to the below screenshot python print 2 decimal places.

Python print 2 decimal places

Python float precision truncate

Firstly, we need to import math module. Then the trunc() function is used to remove all decimal parts from the floating-point numbers and it returns only the integer part of the number.

import math float = 12.16785 print("The value of number is: ",end="") print (math.trunc(float))

After writing the above code (python float precision truncate), Ones you will print “ math.trunc(float)” then the output will appear as a “ The value of a number is: 12 ”. Here, trunc() will print integer value after truncating.

Читайте также:  Java foreach and null

You can refer to the below screenshot for python float precision truncate

Python Float Precision truncate

Python float precision ceil

In Python, the ceil() function is used to return the ceiling value of a number. The ceil value is the smallest integer greater than the number.

import math float = 12.16785 print("The smallest integer greater than number is: ",end="") print (math.ceil(float))

After writing the above code (python float precision ceil), Ones you will print “ math.ceil(float) ” then the output will appear as a “ The smallest integer greater than a number is: 13 ”. Here, we used ceil to print numbers after the ceiling. It will return the smallest integer greater than the given number.

You can refer to the below screenshot for python float precision ceil.

Python Float Precision ceil

Python float precision floor

Python floor() function is used to return the floor value of a number. The floor value is the greatest integer smaller than the number.

import math float = 12.16785 print("The greatest integer smaller than number is: ",end="") print (math.floor(float))

After writing the above code (python float precision floor), Ones you will print “math.floor(float)” then the output will appear as a “ The greatest integer smaller than a number is: 12 ”. Here, we used the floor to print numbers after flooring. It will return the greatest integer smaller than the number.

You can refer to the below screenshot for python float precision floor.

Python Float Precision floor

Python decimal format

To format decimals, we will use str.format(number) where a string is ‘’ and it will format string with a number. Also, it will display the number with 1 number before the decimal and up to 2 numbers after the decimal.

number = 1.345 f = ''.format(number) print(f)

After writing the above code (python decimal format), Ones you will print “ f ” then the output will appear as a “ 1.34 ”. Here, formatting decimals displays numbers with a certain number after the decimal point.

You can refer to the below screenshot for python decimal format.

Python decimal format

Python round numbers

To round numbers in python, we will use the round() function. The round function will round off a number to a given number of digits and makes rounding of numbers easier.

number = 1.345 print(round(number))

After writing the above code (python round numbers), Ones you will print “ number ” then the output will appear as a “ 1 ”. Here, the number 1.345 float number will be rounded to 1.

You can refer to the below screenshot for python round numbers.

Python round numbers

Limiting floats to two decimal points

The round() function returns a floating-point number which will be rounded to specified numbers, and it will round the float to two decimal places.

my_float = 2.13456 limit_float = round(my_float, 2) print(limit_float)

After writing the above code (limiting floats to two decimal points), Ones you will print “limit_float” then the output will appear as a “ 2.13 ”. Here, the round(number) with a float number and 2 as ndigits to round float to two decimal points.

You can refer to the below screenshot for python round numbers.

Limiting floats to two decimal points

You may like the following Python tutorials:

In this tutorial, we learned how to print 2 decimal places in python and also we covered the below topics:

  • Python print 2 decimal places
  • Python float precision truncate
  • Python float precision ceil
  • Python float precision floor
  • Python decimal format
  • Python round numbers
  • Limiting floats to two decimal points

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Python Float: Working With Floating-Point Numbers

Python Float

Besides integers, consisting of whole numbers without fractions, Python also offers us the float type. Perhaps you’ve already seen floats without realizing it. After all, when you divide two integers in Python, the result of that division is often of type float.

In this article, I’ll explain what floats are and how to use them. We’ll also look at an important limitation of floats that you need to be aware of.

What is a Python float?

a Python float is a numerical data type that represents a floating-point number. A floating-point number is a number with a decimal point or exponent notation, indicating that a number is a certain number of digits before and after the decimal point or exponent. For example, the number 1.23 is a floating-point number with one digit before the decimal point and two digits after the decimal point.

Creating floating point numbers

There are multiple ways to create floating-point numbers in Python. Most of the time, you will simply enter the number as-is:

# You can simply enter the number f = 1.45

But you may want to convert a number or a string to a float using the float() function. The variable f will become 2.0 in all cases below:

# f will become 2.0 in all cases below f = float(2.0) f = float(2) f = float("2")

You can also use scientific notation:

Working with Python floats

Working with floats is not much different from working with integers. You can do the usual addition, subtraction, multiplication, and division.

x = 1.45 y = 4.51 # Add x and y z = x + y # Subtract x and y z = x - y # Multiply x and y z = x * y # Divide x and y z = x / y

Round, floor, and upper

With floats, we often need to round numbers. For this, Python has the round function. The round function accepts two arguments: the number itself and an optional precision (the number of decimals). The default for this last number is 0, meaning that it will round to whole integers. Some examples:

>>> f = 1.4567 >>> round(f) 1 >>> round(f, 2) 1.46 >>> f = 1.54 >>> round(f) 2 >>> round(f, 1) 1.5

While round is available without importing, we need to do an import from the math library to floor and ceil a number.

The floor function rounds a float down to the nearest integer while the ceil function rounds a float up to the nearest integer. Here’s an example of how you can import and use these functions:

from math import floor, ceil # Round 1.23 down to the nearest integer x = floor(1.23) # x will be 1 # Round 1.23 up to the nearest integer y = ceil(1.23) # y will be 2

Comparisons

Just like other types of numbers, floats can be compared using comparison operators such as == , != , > , < , >= , and

x = 1.23 y = 4.56 if x == y: print("x and y are equal") else: print("x and y are not equal")

The Python float has limited precision

Let’s do a little experiment. For extra dramatic effect, try this for yourself first:

>>> 0.3 + 0.1 0.4 >>> 0.1 + 3.8 3.9 >>> 0.1 + 0.2 # What is the output of this last statement?

Did you expect the output to be 0.3 like any normal person would? I don’t blame you, but you’re wrong! The output is actually 0.30000000000000004 . As absurd as this might seem, there’s an explanation.

First of all, some fractional numbers are endless. E.g., when you divide 1 by 3, you can round the result to 0.33, 0.333333333, or 0.333333333333333333. No matter what precision you choose, there will always be more 3’s. Since there’s a limited number of bits to store a float number, many numbers are a best-effort approximation. So floating-point numbers have limited precision because they are stored in a finite amount of memory, sometimes leading to unexpected results when performing arithmetic operations on floating-point numbers.

Solving the limited precision

The limited precision of floats is a fundamental property of how floats are represented in computer memory. Therefore, it is not possible to completely eliminate the issue of limited precision when working with floats.

However, there are a few ways that you can mitigate the effects of limited precision when working with floats in Python:

  1. Use the decimal module: The decimal module in the Python standard library provides support for decimal floating-point arithmetic. This allows you to work with decimal numbers that have fixed precision, which can be useful for applications that require more precise calculations than what is possible with regular floats. The downside: floats are much faster than using the decimal pacakge.
  2. Use NumPy: The numpy module is a popular scientific computing library for Python that supports working with arrays of numbers. The numpy module provides a data type called numpy.float128 that allows you to work with higher-precision floating-point numbers than regular floats.
  3. Round your floats: As mentioned earlier, you can use the round function to round a float to a specified number of decimal places. Limiting the number of decimal places used in your calculations can help reduce the strange effects of limited precision, but this method makes your calculations even more imprecise.

Converting floats to other data types

You can convert a float to other data types, such as int or str , using the built-in functions int() and str() . For example, the following code converts the float 1.23 to an integer and a string:

# Convert float to integer my_int = int(1.22) # my_int will be 1 # Convert float to string my_str = str(2.23) # my_str will be "2.23"

Get certified with our courses

Our premium courses offer a superior user experience with small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Course for Beginners

Python Fundamentals II: Modules, Packages, Virtual Environments (2023)

NumPy Course: The Hands-on Introduction To NumPy (2023)

Learn more

This article is part of my Python tutorial. You can head over to the start of the tutorial here. You can navigate this tutorial using the buttons at the top and bottom of the articles. To get an overview of all articles in the tutorial, please use the fold-out menu at the top.

If you liked this article, you might also like to read the following articles:

Источник

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