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
double
will have any unexpected result like nan
error or is it totally safe to follow above steps ? Please guide. (b) In my case, I have two operands both are of type Long
, so shall I convert one to type Int
NaN
when cast to a double. For this specific case, as long as you don't divide by 0, you should be fine. 2) You can directly convert the long to a double, although you will lose precision if your long is in the 2^52 to 2^63 range, either positive or negative.
Jul 21, 2021 at 13:22
This is an extension function to do it everywhere:
fun Int.divideToPercent(divideTo: Int): Int {
return if (divideTo == 0) 0
else (this / divideTo.toFloat() * 100).toInt()
}
and use it like this:
val pecent = 10.divideToPercent(20)
The percent
will be 50.
You can even make it an infix fuction:
infix fun Int.percentOf(value: Int): Int {
return if (this == 0) 0
else (value / this.toFloat()).toInt()
}
and use it like this:
val pecent = 10 percentOf 200
The percent
will be 20
val percentage = (count * 100) / totalCount
var percentage = 100.0 * count / totalCount