Types
- Byte
- Short
- Int
- Long
- Float
- Double
Convert string to number
package examples
fun main() {
println("1.01".toIntOrNull()) // null (not 1)
println("1".toInt())
println("1.01".toDouble())
println("1.01".toBigDecimal())
println("1.01e".toBigDecimal()) // NumberFormatException
}
Convert int to double
package examples
fun main() {
val i = 1
val d = 0.5
println(i - d) // 0.5
println(i.javaClass) // int
println(i.toDouble()) // 1.0
}
Format number to string: %
package examples
fun main() {
println("%.2f".format(1.123456)) // 1.12
}
Convert Double to Int
package examples
import kotlin.math.roundToInt
fun main() {
val d15 = 1.5
val d14 = 1.4
println(d15.roundToInt()) // 2
println(d14.roundToInt()) // 1
println(d15.toInt()) // 1
println(d14.toUInt()) // 1
val md15 = -1.5
val md14 = -1.4
println(md15.roundToInt()) // -1
println(md14.roundToInt()) // -1
println(md15.toInt()) // -1
println(md14.toUInt()) // 0
}
沒有留言:
張貼留言