What does double slash // operator do in Python
When dealing with numbers, we sometimes need to truncate a float value by removing its decimal places. Unlike, Java where we simply typecast the value to an integer to get the truncated value, Python by default assumes the datatype of any input as integer or float.
Round vs Truncate
However, rounding a value is not the same as truncating it. While rounding it returns the nearest integer value based on the principle of mathematics whereas truncating just removes the decimal parts from the float datatype.
Truncating with the double slash operator in Python
To get the truncated value, we can use the integer division operator in Python. When we are dividing any number from another, we can simply use the double forward slash. This operator will just keep the whole number component when we divide the left by the right number.
a = 11 b = 3 # rounded value of the simple division to the nearest integer c1 = round(a/b) # truncated value of the division with just the whole number part c2 = a // b print(c1) print(c2)
Read more: Increment Operator in Python because ++ operator does not work in Python
Leave a Reply