Search code examples
androidmathkotlin

How to calculate percentage in Kotlin


I need to calculate a percentage in Kotlin. I tried but failed to get the correct answer:

var percentage = (count/totalCount) * 100
it.toast("Percentage: $percentage")

What is the proper syntax in Kotlin?


Solution

  • Most likely, you're struggling with the fact that applying the division operator on two integers will result in an integer division being performed, yielding an integer result.

    The trick is to promote one of the operands to a floating point type:

    var percentage = (count.toDouble() / totalCount) * 100