如何将数字字符(0-9)转换为数字值?

Char.toInt()返回字符的ASCII码,而不是数字值。 那么如何将Char转换为具有正确数值的整数呢?

你也可以将它转换为一个String ,然后使用toInt() ,这可能会更明显。

 fun Char.getNumericValue(): Int { if (!isDigit()) { throw NumberFormatException() } return this.toString().toInt() } 

回答:

您可以在Char类中创建一个扩展,它将从toInt()返回的ASCII代码中减去48。 这会给你正确的字符数值!

 fun Char.getNumericValue(): Int { if (this !in '0'..'9') { throw NumberFormatException() } return this.toInt() - '0'.toInt() }