Yash Jain
Yash Jain

Reputation: 461

How to multiply variables in a string literal in Kotlin?

Here is an example:

var quantity: Int = 3
var price: Int = 20 
var total: String = "$quantity*$price"

But the the var total prints the following:

Output: 320

The desired outcome should be 60. In java, one would simply do a string literal like this to multiply price and quantity:

String price = "" + price*quantity

Upvotes: 1

Views: 2096

Answers (3)

jbach04
jbach04

Reputation: 43

I was trying to do something similar to this, but with adding the two together. It does appear this method will work with both adding and multiplication. Here is code form my app below:

val sampTonAdded = "${sublotTonEdit.toInt() + ranTonEdit.toInt()}"

It seemed as though adding .toInt() fixed my issues.

Upvotes: 0

Ben Shmuel
Ben Shmuel

Reputation: 1989

Using StringBuilder might be also a good solution if you will need to append() or insert() to total

For example:

var quantity: Int = 3
var price: Int = 20
var total = StringBuilder().apply {
    append(price * quantity)
}
...
...
total.apply {
      insert(0, if (condition) "total amount:" else "current amount:")
}
// total amount: 60 or current amount: 60 depends on your condition

Upvotes: 1

Gourav Rana
Gourav Rana

Reputation: 64

Try

var total: String = "${quantity*price}"

Upvotes: 0

Related Questions