i divide two Integers (e.x 3/6) and i'm trying to get a result of 0.500000 in kotlin. i've tried some solutions but none of them solve my problem like.
val num = BigDecimal(3.div(6)) println("%.6f".format(num))
but the result is 0.000000
Unlike Java, these are automatically assigned Int type in Kotlin. Now, to find the quotient we divide dividend by divisor using / operator. Since, both dividend and divisor are Int , the result will also be computed as an Int .
Kotlin arithmetic operators This is all familiar from the mathematics. The % operator is called the remainder or the modulo operator. It finds the remainder of division of one number by another. For example, 9 % 4 , 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.
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.
You might have better luck with:
val num = 3.toBigDecimal().divide(6.toBigDecimal()) println(num) // prints 0.5
You have to convert both numbers to BigDecimal for the method to work. This will show the exact quotient, or throw an exception if the exact quotient cannot be represented (ie a non-terminating decimal).
You can set the scale and rounding mode as follows:
val num = 3.toBigDecimal().divide(6.toBigDecimal(), 4, RoundingMode.HALF_UP) println(num) // prints 0.5000
Link to reference article
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With