Search code examples
kotlindivisioninteger-division

How to divide two Int a get a BigDecimal in Kotlin?


I want to divide two Integers and get a BigDecimal back in Kotlin.

E.g. 3/6 = 0.500000.

I've tried some solutions, like:

val num = BigDecimal(3.div(6))
println("%.6f".format(num))

// The result is: 0.000000

but none of them solve my problem.


Solution

  • 3 and 6 are both Int, and dividing one Int by another gives an Int: that's why you get back 0. To get a non-integer value you need to get the result of the division to be a non-integer value. One way to do this is convert the Int to something else before dividing it, e.g.:

    val num = 3.toDouble() / 6
    

    num will now be a Double with a value of 0.5, which you can format as a string as you wish.