I am working on a console application in Kotlin where I accept multiple arguments in main()
function
fun main(args: Array<String>) { // validation & String to Integer conversion }
I want to check whether the String
is a valid integer and convert the same or else I have to throw some exception.
How can I resolve this?
Convert String to Double in Kotlin The toDouble() method converts the string to a Double, It returns NumberFormatException if it sees the string is not a valid representation of a Double.
fun String. getAmount(): String { return substring(indexOfFirst { it. isDigit() }, indexOfLast { it. isDigit() } + 1) .
In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.
On top of that, we successfully converted String to Int, Float, Double, Long in Kotlin/Android. We barely scratched the surface; however, if you want to dig deep, then you should check out the Types in Kotlin and Kotlin API.
Run this Kotlin program. Just to prove that it is an int, we are adding a value of 10 to it and printing the result. In this example, we shall first initialize a string. Secondly we call Integer.parseInt () with the string as arguemnt the string and store the returned int value.
String to Int Conversion In its simplest scenario, we can use the toInt () extension function to convert a String to its corresponding Int value. When the String contains valid numeric content, everything should work smoothly:
If the value of the specified string is negative, the sign should be preserved in the resultant integer. 1. Using toInt () function You can easily convert the given string to an integer with the toInt () function. It throws a NumberFormatException if the string does not contain a valid integer.
You could call toInt()
on your String
instances:
fun main(args: Array<String>) { for (str in args) { try { val parsedInt = str.toInt() println("The parsed int is $parsedInt") } catch (nfe: NumberFormatException) { // not a valid int } } }
Or toIntOrNull()
as an alternative:
for (str in args) { val parsedInt = str.toIntOrNull() if (parsedInt != null) { println("The parsed int is $parsedInt") } else { // not a valid int } }
If you don't care about the invalid values, then you could combine toIntOrNull()
with the safe call operator and a scope function, for example:
for (str in args) { str.toIntOrNull()?.let { println("The parsed int is $it") } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With