Kotlin - Numbers

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
}


沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...