In this tutorial, we will learn Why does the division gets rounded to an integer in python we have different ways of dividing two digits like by ‘/’ or ‘//’ ‘/’ is used for getting the exact value after dividing whereas in case of ‘//’ it is not the same case it will simply get floor value.
And here in this post, we will get to know the exact differences between both the ways to divide the numbers and when we need which one or we can say when we should use which operator to divide the number.
Division
As we know When we divide a number there is a prob that we might get the output in the form of decimal numbers so at some times we might want to avoid such cases when we do not want to get the decimal values in that case we have a number of ways to avoid the decimal values which could be round off, floor values and we can simply truncate the decimal values.
The use of all three methods depends upon the requirements of the output as at some times we simply need the floor value and at the time we need to round off the digits that we got after calculations as the floor values get changed in case of round off.
Here will take the example of all three cases and try to find out the difference between them and how they all differ from each other.
Let’s understand the difference between all of these.
Truncation:
import math # Truncating a float to an integer num = 3.14159 truncated_num = int( num) print( truncated_ num) # Output: 3 # Truncating a decimal to a certain number of decimal places dec = 3.14159 truncated_ dec = math.trunc( dec * 100) / 100 print( truncated_ dec) # Output: 3.14
Rounding
import math # Rounding a float to the nearest integer num = 3.6 rounded_ num = round( num) print(rounded_num) # Output: 4 # Rounding a decimal to a certain number of decimal places dec = 3.14159 rounded_ dec = round( dec, 2) print (rounded_ dec) # Output: 3.14
Flooring
import math # Flooring a float to the nearest integer num = 3.6 floored_ num = math. floor( num) print( floored_ num) # Output: 3 # Flooring a decimal to a certain number of decimal places dec = 3.14159 floored_ dec = math. floor( dec * 100) / 100 print( floored_ dec) # Output: 3.14
To learn more about Why does the division gets rounded to an integer visit: Rounding off of decimal numbers.
To learn more about python solutions of problems and concepts visit: Python Tutorials And Problems.
To learn more solutions and concepts of different other programming languages visit: beta python programming languages Solutions.