Home > Mobile >  How to output mathematical operation alongside the calculation in simple Kotlin Calculator
How to output mathematical operation alongside the calculation in simple Kotlin Calculator

Time:08-31

I'm very new to Kotlin programming and can't seem to figure out a working solution. I need to have the output include the mathematical operation and have it equal the calculation as the output eg. 1 1=2 needs to be the output instead of just the answer My addition function is below Any help if greatly appreciated.

fun add(){
        var input1 = firstvalue.text.toString().trim().toBigDecimal()
        var input2 = secondvalue.text.toString().trim().toBigDecimal()
        calcoutput.text = input1.add(input2).toString()
    }

CodePudding user response:

This is probably a good time to learn about string templates!

You can add the value of a variable to a string like this:

val name = "Wuffles"
println("My dog's name is $name")

That will call toString() on the variable and add the result into the final string. If you need to access anything more complicated than a basic variable name, e.g. a property on a thing, or even the result of some code, you wrap it in {} so you end up with ${something}:

println("First input: ${firstValue.text}")
println("Result: ${input1   input2}")

So what you're basically doing is creating a string with some fixed text, and some places where you insert a value. See if you can work out how to create the string "1 1 = 2" except with the correct values inserted!

  • Related