Dividing Integers


#1

Dividing two Int’s returns another Int. This behavior is the same as in Java and I find it to be very dangerous and un-intuitive.
For example: The expression 5/2 evaluates to 2 instead of the correct value of 2.5
To get the correct value, the user must first parse one of the Int’s to Double like this:
5/2.toDouble()
This behavior of silent rounding is almost never wanted and can be quite hard to debug since 5/2 is mathematically correct.
I propose a change of Int.div(Int):Int to Int.div(Int):Double
Although this might some existing code due to Incompatibility of Double and Int, I think it will prevent enough bugs in the future to make it worth it.


#2

Mathematically speaking the current behaviour is correct. This is called integer devision and results in the quotient as an answer. For more information see: https://en.wikipedia.org/wiki/Division_(mathematics)

But I suspect you have a background in a language like Javascript, which only has one numeric type, and expect the same behaviour here. Your statement that this behaviour is “almost never wanted” is just your own perspective. In general sense it will not hold.


#3

In addition, mainstream compiled languages all have the same behaviour as Kotlin. Not only that, there is a special CPU instruction for it that is much faster than floating point division. To have the suggested behaviour would be very surprising for many users of the language, and would under water involve a conversion of both parameters to doubles (note that float cannot represent the full range of integer values). In the case of long numbers you could even get an incorrect answer due to doubles not capturing the full precision of 64 bit integers.


#4

This is very unlikely to be changed for compatibility reasons


#5

From a backwards compatibility standpoint and a Java similarity standpoint, it would be wrong to change the behaviour of the division operator like this.

You can do this with an infix extension function instead.
infix fun Int.fdiv(i: Int): Double = this / i.toDouble();

Then you could do this kind of division like this:
1 fdiv 2

If a new operator would be introduced for this, it could be perhaps be /. or ./
The precision yielded by this operator (single or double) would have to be inferred somehow, or specified with a prefix or suffix.
It might look out of place and would cause confusion whether or not one should use the ordinary division operator when both operands are not ints.