omoor
omoor

Reputation: 73

How to make a string exercise into int in kotlin?

Everything I tried gives an Error, it can handle the numbers but not the "+",what I want is the result to be "10". I'm attempting to make a calculator in android studio... This is what I tried:

var sum = "5+5"
val num = sum.toInt()
exercise.text = "$num" //the text displayed on the screen

Upvotes: 0

Views: 310

Answers (2)

omoor
omoor

Reputation: 73

I followed a tutorial and I can now answer my own question: You can use implementation 'net.objecthunter:exp4j:0.4.8' in your build gradle, then use .append(string) to add a string into your text and then use

val expression = ExpressionBuilder(Text.text.toString()).build()
val result = expression.evaluate()
val longResult = result.toLong()
if(result == longResult.toDouble())
   Text.text = "=$longResult"
else
    Text.text = "=$result"

to evaluate and paste the result in the text you have

Upvotes: 0

Anshul
Anshul

Reputation: 1669

Use eval function insted of toInt() , just a little research See

*Above is only available for Kotlin/Js.

Upvotes: 1

Related Questions