18

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.

philipjkim
  • 3,999
  • 7
  • 35
  • 48

4 Answers4

36

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
hotkey
  • 140,743
  • 39
  • 371
  • 326
  • I only find an abstract `Number`, where is this concrete `Number`? – Ray Wang Aug 23 '17 at 03:12
  • That's it, there is only one `Number`. The implementation mentioned in the answer is an intrinsic generated by kotlinc. Thus there is no virtual method you could look at. – voddan Aug 23 '17 at 06:12
0

First of all, this documentation is straight up copied from Java's documentation.

As far as I know it only truncates the decimal points, e.g. 3.14 will become 3, 12.345 will become 12, and 9.999 will become 9.

Reading this answer and the comments under it suggests that there is no actual rounding. The "rounding" is actually truncating. The rounding differs from Math.floor that instead of rounding to Integer.MIN_VALUE it rounds to 0.

Mibac
  • 8,990
  • 5
  • 33
  • 57
0

use this roundToInt() in kotlin

import kotlin.math.roundToInt
fun main() {
    var r = 3.1416
    var c:Int =  r.roundToInt() 
    println(c)
}
Mosfeq Anik
  • 89
  • 1
  • 4
0

Use the function to.Int(), and send the value to the new variable which is marked as Int:

val x: Int = variable_name.toInt()

sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
Madhav7890
  • 71
  • 1
  • 4