João Carlos
João Carlos

Reputation: 1605

How to convert character to its integer value in kotlin?

I'm trying to convert an string to its integer value in Kotlin, using the toInt() function that i found in this answer, but I'm getting the ascii value instead.

What I'm doing wrong?

var input = "8569 2478 0383 3437"

val regex = "[^0-9]".toRegex()
var value = regex.replace(input, "")

val iterator = value.iterator()

var sum : Int = 0
var v : Int
for((index, value) in iterator.withIndex()){
    if(index % 2 == 0){
        var v = value.toInt() * 2 
        if(v > 9) v -= 9

        print("$v:$value ")
        sum += v
    }else{
        print("$value ")
        sum += value.toInt()
    }
}

executing this code above, this is the printed numbers

103:8 5 99:6 9 91:2 4 101:7 8 87:0 3 103:8 3 93:3 4 93:3 7

and I was expecting some like this

8:8 5 6:6 9 2:2 4 7:7 8 0:0 3 8:8 3 3:3 4 3:3 7

Upvotes: 4

Views: 6451

Answers (2)

Todd
Todd

Reputation: 31720

Note: I have updated this answer because Kotlin 1.5 has a function to do this directly.

In your loop, value is a Char, and toInt() on Char returns its character number. Therefore, you'll have perform a conversion to get its digit representation.

Starting in Kotlin 1.5, you can use digitToInt() to accomplish this:

var v = value.digitToInt()

Before Kotlin 1.5, we would need to convert to a String and then an Int:

var v = value.toString().toInt() * 2

Upvotes: 8

Willi Mentzel
Willi Mentzel

Reputation: 29914

If you are targeting the JVM, you can use Character.getNumericValue:

val v = Character.getNumericValue(value) * 2

so there is no need to do two casts.

If you want to be platform independent, go with Todd's answer.

Upvotes: 0

Related Questions