Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to Calculate Percentage in Kotlin syntax?

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?

like image 494
Abdul Mateen Avatar asked Sep 29 '19 14:09

Abdul Mateen


2 Answers

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
like image 83
Robby Cornelissen Avatar answered Nov 06 '22 05:11

Robby Cornelissen


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.

like image 23
Vahid Avatar answered Nov 06 '22 05:11

Vahid