On the official API doc, it says:

以整数形式返回此数字的值,这可能涉及舍入或截断.

我想要截断,但不确定.有人能解释may involve rounding or truncation的确切含义吗?

p.s.: In my unit test, (1.7).toInt() was 1, which might involve truncation.

推荐答案

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.

在Kotlin中,Double运算遵循IEEE 754标准,Double.toInt()转换的语义与casting double to int in Java相同,即正常数向零舍入,舍go 小数部分:

println(1.1.toInt())  // 1
println(1.7.toInt())  // 1
println(-2.3.toInt()) // -2
println(-2.9.toInt()) // -2

Kotlin相关问答推荐

Android前台服务 list —Altbeacon

Kotlin-删除按钮周围的空格

如何在操作系统版本上正确获取Room数据库的路径>;=26 sdk?

如何检测一个值是否是Kotlin中的枚举实例?

为什么这两个 Kotlin 协程函数不一样?

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

如何使用 Hilt 注入应用程序:ViewModel 中的上下文?

AIDL 中的 Parcelize 注释:Incompatible types: Object cannot be converted to MyCustomObject

如何使用 Findbugs 避免 kotlin 文件

在粘贴时将 java 转换为 kotlin

在 Scaffold Jetpack Compose 内的特定屏幕上隐藏顶部和底部导航器

如何在 Kotlin 中判断数组类型(不是泛型类型)

如何在 Android Studio 3.1.3 中查看 Kotlin 中有趣的源代码?

使用kotlinx协同程序测试中的类时出错

Jetpack Compose State:修改类属性

Kapt不适用于Android Studio 3.0中的AutoValue

Android EditText 协程go 抖操作符,如 RxJava

(kotlin的Moshi)@Json vs@field:Json

在 Kotlin 中编写一个等于 Int.MIN_VALUE 的十六进制整数文字

在多平台子元素中使用kapt