Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert digit to character in Kotlin?

Tags:

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).

like image 485
Nicholas Miller Avatar asked Oct 31 '25 12:10

Nicholas Miller


2 Answers

val character = '0' + number

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

like image 120
Ilya Avatar answered Nov 03 '25 10:11

Ilya


Kotlin stdlib provides this function since 1.5.0.

fun Int.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
like image 22
JohnKoch Avatar answered Nov 03 '25 10:11

JohnKoch