How to Solve FloatingPointError in Python

To solve FloatingPointError in Python, use the round() method. The round() is a built-in Python method that rounds a number to only two decimals. The round() method returns a floating-point number, a rounded version of the provided number, with the specified number of decimals.

FloatingPointError in Python

FloatingPointError in Python is an ArithmeticError that occurs when there is an error in arithmetic calculations. A floating-point number is a number that consists of two parts in which, one is for whole numbers, and the other one is for decimal numbers. A decimal point separates these two. Memory can hold a floating-point up to some limit.

The FloatingPointError is raised when the decimal point limit crosses the memory limit.

Example

a = 3
b = 2
c = a / b
print(c)

Output

1.5

If we divide 3 by 2, the result is 1.5. 1.5 is the floating-point number, 1 is the whole number, and .5 is the decimal number. 

Now let us see the same program with different values.

a = 10
b = 3
c = a / b
print(c)

Output

3.3333333333333335

When we execute this program, the expected output will be 3.3333. It has no ending. This is the best example describing the floating-point exception. But Python automatically rounds them to the nearest decimal number.

We can solve the FloatingPointError error by using the try-except block. In the try block, we can see the division operation code. And in except block, we will handle the FloatingPointError.

Python smartly handles the exception without giving trouble to the user. To manually handle the FloatingPointError exception, use the round() method. We can use the round() method to round the decimal places. We can pass the number of decimal precisions we want in the output.

a = 10
b = 3
c = a / b

print(round(c, 3))

Output

3.333

In this example, we want the output in three decimal places. There are other methods similar to the round() method like ceil() and floor() methods.

The ceil() is a built-in Python method used to round the number to the nearest greatest number.

The floor() is a built-in Python method used to round the number to the nearest lowest number.

Now, let us see how to use the try-except block for handling this exception.

try:
 a = 10
 b = 3
 c = a / b
 print(c)

except FloatingPointError:
 print("Floating point error has occurred")

Output

5.0

The program gets executed and prints the result as 5. If the floating-point error occurs, the exception block gets executed. 

Conclusion

We don’t want to care about FloatingPointError because this error will automatically be taken care of by Python. If FloatingPointError occurs, we can use the try-except clause for handling it.

That’s it for this tutorial.

See also

TypeError: must be str, not int

TypeError: ‘float’ object is not iterable

TypeError: list indices must be integers or slices, not str

Leave a Comment