kotlin Int型に変換する

kotlin Int型に変換する

kotlinで、Int型に変換する手順を記述してます。「toString」で可能です。

環境

  • OS windows11 home
  • java 19.0.1
  • kotlin 1.7.20-release-201

手順

Int型に変換するには、「toString」を使用します。

値.toInt()

実際に、変換してみます。

fun main() {

    var x: String = "123"

    check(x.toInt()) // 123 is Int  

}

fun check(x: Any?){
    when (x) {
        is Byte -> println("$x is Byte")
        is Int -> println("$x is Int")                
        is Double -> println("$x is Double")
        is Char -> println("$x is Char")
        is String -> println("$x is String")        
        is Boolean -> println("$x is Boolean")  
    }
}

少数を指定するとエラーが発生します。

fun main() {

    var x: String = "123"

    check(x.toInt()) 
  // Exception in thread "main" java.lang.NumberFormatException: For input string: "123.45"

}

fun check(x: Any?){
    when (x) {
        is Byte -> println("$x is Byte")
        is Int -> println("$x is Int")                
        is Double -> println("$x is Double")
        is Char -> println("$x is Char")
        is String -> println("$x is String")        
        is Boolean -> println("$x is Boolean")  
    }
}

Char型

Char型の場合は、文字コードと認識されて変換されます。

fun main() {

    var x: Char = '1'
    var y: Char = '2'

    check(x.toInt()) // 49 is Int 
    check(y.toInt()) // 50 is Int

}

fun check(x: Any?){
    when (x) {
        is Byte -> println("$x is Byte")
        is Int -> println("$x is Int")                
        is Double -> println("$x is Double")
        is Char -> println("$x is Char")
        is String -> println("$x is String")        
        is Boolean -> println("$x is Boolean")  
    }
}

Double型

Double型の場合は、切り捨てが行われます。

fun main() {

    var x: Double = 123.45
    var y: Double = 123.99

    check(x.toInt()) // 123 is Int
    check(y.toInt()) // 123 is Int

}

fun check(x: Any?){
    when (x) {
        is Byte -> println("$x is Byte")
        is Int -> println("$x is Int")                
        is Double -> println("$x is Double")
        is Char -> println("$x is Char")
        is String -> println("$x is String")        
        is Boolean -> println("$x is Boolean")  
    }
}