In this Kotlin tutorial, you shall learn how to read a float value from console entered by user, using readLine() function, with example programs.
Kotlin – Read float value from console
To read a floating point value input by user via console in Kotlin, we can use readLine() function and String.toInt() method.
When readLine() function is executed, the prompt appears in the console for the user to enter an input. User can input a value and after entering all the input, press enter or return key. The readLine() function returns the entered value as a String.
The syntax to call readLine() function is
readLine()
Please note that the function can also return a null value.
Once we got the string value, we convert it to a floating point value using String.toFloat() method, as shown in the following. Please note that we have used safe call ?.
operator.
readLine()?.toFloat()
Example
In the following program, we read a floating point number to n
from user input. We then print the entered value back to console.
Main.kt
fun main() {
print("Enter a float value : ")
val n = readLine()?.toFloat()
println("You entered : $n")
}
Output #1
Enter a float value : 3.14
You entered : 3.14
Output #2
Enter a float value : 3.14asdf
Exception in thread "main" java.lang.NumberFormatException: For input string: "3.14asdf"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.base/java.lang.Float.parseFloat(Float.java:455)
at MainKt.main(Main.kt:3)
at MainKt.main(Main.kt)
When we entered an invalid value for a float, parsing failed and NumberFormatException is thrown.
Conclusion
In this Kotlin Tutorial, we learned how to read a floating point value from console input using readLine() function and String.toFloat() method.