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

We have Math.floor() method to round down in JavaScript, and the equivalent of this functionality is not available in Python. We can use the round() function in Python to get a value to the nearest integer. It will return a floating-point number that is rounded with the specified number of decimals. The round() function will return the nearest integer value if the parameter for the number of decimals is not passed.

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)
4
3

Read more:  Increment Operator in Python because ++ operator does not work in Python

Leave a Reply

Your email address will not be published. Required fields are marked *