'How to convert digit to character in Kotlin?

I'm trying to find the simplest way to convert a digit (0..9) into the respective character '0'..'9' in Kotlin.

My initial attempt was to write the following code:

fun convertToCharacter() {
    val number = 0

    val character = number.toChar()
    println(character)
}

Of course, after running, I quickly saw that this produces \u0000, and not '0' like I expected. Then, remembering from how to do this in Java, I modified the code to add '0', but then this would not compile.

fun convertToCharacter() {
    val number = 0

    val character = number.toChar() + '0'
    println(character)
}

What is the appropriate way to convert a number into its respective character counterpart in Kotlin? Ideally, I'm trying to avoid pulling up the ASCII table to accomplish this (I know I can add 48 to the number since 48 -> '0' in ASCII).



Solution 1:[1]

val character = '0' + number

is the shortest way, given that the number is in range 0..9

Solution 2:[2]

Like you said, probably the easiest way to convert an Int to the Char representation of that same digit is to add 48 and call toChar():

val number = 3
val character = (number + 48).toChar()
println(character) // prints 3

If you don't want to have the magic 48 number in your program, you could first parse the number to a String and then use toCharArray()[0] to get the Char representation:

val number = 3
val character = number.toString().toCharArray()[0]
println(character) // prints 3

Edit: in the spirit of the attempt in your question, you can do math with '0'.toInt() and get the result you were expecting:

val number = 7
val character = (number + '0'.toInt()).toChar()
println(number) // prints 7

Solution 3:[3]

Kotlin stdlib provides this function since 1.5.0.

fun digitToChar(): Char

Returns the Char that represents this decimal digit. Throws an exception if this value is not in the range 0..9.

If this value is in 0..9, the decimal digit Char with code '0'.code + this is returned.

Example

println(5.digitToChar()) // 5
println(3.digitToChar(radix = 8)) // 3
println(10.digitToChar(radix = 16)) // A
println(20.digitToChar(radix = 36)) // K

Solution 4:[4]

How about 0.toString() instead of 0.toChar() ? If you are specifically after single digits, then 0.toString()[0] will give you a Char type

Solution 5:[5]

You can use an extension like this:

fun Int.toReadableChar(): Char {
    return ('0'.toInt() + this).toChar()
}

You can apply this to any other class you want :)

Example:

println(7.toReadableChar())
>> 7

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ilya
Solution 2
Solution 3 Ilya
Solution 4 David Soroko
Solution 5 Razzlez