On the official API doc, it says:
Returns the value of this number as an Int, which may involve rounding or truncation.
I want truncation, but not sure. Can anyone explain the exact meaning of may involve rounding or truncation
?
p.s.: In my unit test, (1.7).toInt()
was 1, which might involve truncation.
round() Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.
The answer is Yes. Java does a round down in case of division of two integer numbers.
The KDoc of Double.toInt()
is simply inherited from Number.toInt()
, and for that, the exact meaning is, it is defined in the concrete Number
implementation how it is converted to Int
.
In Kotlin, the Double
operations follow the IEEE 754 standard, and the semantics of the Double.toInt()
conversion is the same as that of casting double
to int
in Java, i.e. normal numbers are rounded toward zero, dropping the fractional part:
println(1.1.toInt()) // 1
println(1.7.toInt()) // 1
println(-2.3.toInt()) // -2
println(-2.9.toInt()) // -2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With