Andrew
Andrew

Reputation: 2157

How to increment the result of division when it contains remainder of the division?

Maybe this question was asked previously but I didn't find a solution of my problem. So, I have one number like general count and I have to get the result of division. But, I have to increment the result if it contains remainder. I tried to create own function:

 private fun mod(count: Int): Double {
        val mainCount: Double
        val remainder = count % 50

        mainCount = if (remainder > 0) {
            count.toDouble() / 50+1
        } else {
            count.toDouble() / 50
        }

        return mainCount
    }

but it didn't help, then I used this function:

val df = DecimalFormat("0")
df.roundingMode = RoundingMode.HALF_EVEN
Log.i("m", df.format(count/50).toString())

but in logs I get the main number without remainder. For example I have smth like that:

main count - 112
result of division - 2.24
what I want to get - 3

Maybe I did smth wrong?

Upvotes: 0

Views: 1211

Answers (3)

Andy Turner
Andy Turner

Reputation: 140494

As far as I can see, you are simply trying to round the result up.

The simplest way to do this is to add (denominator - 1) to the numerator. So (in Java), the entire method could be reduced to:

return (count + 49) / 50;

Upvotes: 5

Firoz Memon
Firoz Memon

Reputation: 4680

I have updated your code snippet. Hope it helps.

    val mainCount: Double
    val remainder = count % 50

    mainCount = count.toDouble() / 50
    val finalMainCount = if (remainder > 0) {
        mainCount.toInt() + 1
    } else {
        mainCount.toInt()
    }

    println(finalMainCount)

    return finalMainCount

Upvotes: 1

Kuldeep Rathee
Kuldeep Rathee

Reputation: 290

just add +1 in the main court if the remainder is greater then 0 and less then 50. like if(reminder >0 && reminder <50) mainCount++;

Upvotes: 1

Related Questions