16

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?

2
  • 3
    If count and totalCount are integers then count/totalCount does integer division. Change to: var percentage = 100.0 * count / totalCount
    – forpas
    Sep 29, 2019 at 14:22
  • val size = 10f val percentage = percentTrip / totalTrip * 100f
    – Ankit Tale
    Sep 29, 2019 at 14:24

3 Answers 3

50

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
5
  • Great man but its return value in point but we need integer values in case of percentage? Sep 29, 2019 at 15:02
  • 4
    Convert back toInt() Sep 29, 2019 at 15:03
  • Hi @RobbyCornelissen: a) Changing type of one operand to 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
    – SVK
    Jul 21, 2021 at 12:11
  • 1) I'm not aware of any integer value that will produce 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
  • @SVK Forgot to tag you. See comment above. Jul 21, 2021 at 13:30
7

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

1
  • You have a mistyped variable pecent. Shouldn't it be "percent"? Feb 19, 2022 at 21:11
-1
val percentage = (count * 100) / totalCount 
1
  • It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code. Feb 19, 2022 at 21:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.