reza.fathi921
reza.fathi921

Reputation: 13

converting a string to int in kotlin There is a problem

why result is mines? my problem is converting a string to int in kotlin .

class Test{
    val x="200000000"
    val y="11"
}


fun main(){
    val test=Test()
    println(test.x.toInt())
    println(test.y.toInt())
    val z=(Integer.parseInt(test.x))*(Integer.parseInt(test.y))
//or :val z=(test.x.toInt())*(test.y.toInt())
    println(z)

}

result :

200000000

11

-2094967296

Upvotes: 0

Views: 2606

Answers (1)

Joffrey
Joffrey

Reputation: 37829

You're witnessing an integer overflow.

Int in Kotlin (like in Java) represents 32-bit signed integers, so their maximum value is 2,147,483,647.

What you're trying to do is multiply 200,000,000 by 11, which would yield 2,200,000,000 - more than the maximum value. So only the least significant bits of that number can be stored in the 32-bit of the integer, and you end up somewhere in the negative numbers.

If you want to reach this kind of values, you should either use UInt (unsigned integers, which can go twice higher), Long (which are 64-bit and thus can reach much much higher), or other more complex types like BigInteger.

Here is an example with Long:

val x = "200000000"
val y = "11"
val z = x.toLong() * y.toLong()
println(z) // 2200000000

Upvotes: 3

Related Questions