[SOLVED] How to convert an arithmetic expression of a string type to an integer in Kotlin?


This is my code after running this piece of code, I am getting exception:

    fun main() {
    var str = "(100 + 50)/2"
    var sum = str.toInt()

Exception with stack trace is given below:

Exception in thread "main" java.lang.NumberFormatException: For input string: "(100 + 50)/2"
 at java.lang.NumberFormatException.forInputString (:-1) 
 at java.lang.Integer.parseInt (:-1) 
 at java.lang.Integer.parseInt (:-1)


You cannot evaluate arithmetic in string expressions natively in kotlin or java. Either use a library (like exp4j, Javaluator, and SEpl) or write your own (refer to this thread).

Answered By – kcode

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *