Converting a String to a Numeric Type
If you were to run Tavern.kt right now, you would see a compilation error. This is because the price variable that you are currently passing to performPurchase is a string, and the function expects a double. To the human eye, “5.91” might look like a number, but the Kotlin compiler sees it differently, because it was split from the menuData string.
The good news is that Kotlin includes functions that convert strings to different types – including numbers. Some of the most commonly used of these conversion functions are:
-
toFloat
-
toDouble
-
toDoubleOrNull
-
toIntOrNull
-
toLong
-
toBigDecimal
Attempting to convert a string of the wrong format will throw an exception. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access