Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which method is used in Kotlin's Double.toInt(), rounding or truncation?

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.

like image 896
philipjkim Avatar asked Aug 23 '17 02:08

philipjkim


People also ask

How do you round a double to int?

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.

Does Java round up or down when casting to int?

The answer is Yes. Java does a round down in case of division of two integer numbers.


Video Answer


1 Answers

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
like image 139
hotkey Avatar answered Oct 19 '22 20:10

hotkey