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?
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
This is an extension function to do it everywhere:
fun Int.divideToPercent(divideTo: Int): Int {
return if (divideTo == 0) 0
else (this / divideTo.toFloat()).toInt()
}
and use it like this:
val pecent = 10.divideToPercent(20)
The percent
will be 50.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With