Char.toInt()
returns the ASCII code of the character, rather than its numeric value. So how do I convert the Char to an integer with the correct numeric value instead?
Asked
Active
Viewed 2,994 times
2

Incinerator
- 2,589
- 3
- 23
- 30
-
1On JVM there is `java.lang.Character.getNumericValue()`: https://stackoverflow.com/questions/4968323/java-parse-int-value-from-a-char/21441921#21441921 – Vadzim Dec 08 '17 at 12:17
-
1I think that the linked dup question is more specific and is unappropriately titled to close this one as duplicate. – Vadzim Dec 08 '17 at 12:20
2 Answers
6
Answer:
You can create an extension on the Char class which substracts 48 from the ASCII code returned by toInt()
. This will give you the proper numerical value of the character!
fun Char.getNumericValue(): Int {
if (this !in '0'..'9') {
throw NumberFormatException()
}
return this.toInt() - '0'.toInt()
}

Incinerator
- 2,589
- 3
- 23
- 30
-
3This is technically incorrect because `isDigit` will return `true` for characters which are not necessarily `0-9`. `١`, the character `'ARABIC-INDIC DIGIT ONE' (U+0661)`, **is a digit**, but `toInt() - 48` will return 1585 instead. You may want to use `this in '0'..'9'` instead. – Salem Dec 08 '17 at 12:12
-
4
You could also convert it to a String
and then use toInt()
which might be more obvious.
fun Char.getNumericValue(): Int {
if (!isDigit()) {
throw NumberFormatException()
}
return this.toString().toInt()
}

s1m0nw1
- 76,759
- 17
- 167
- 196
-
1Indeed, but I suspect it's not as efficient if I need to run the operation a large number of times? Please correct me if I'm wrong! – Incinerator Dec 08 '17 at 13:39