Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to divide two integer into decimal in kotlin?

Tags:

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

like image 272
Alif Al-Gibran Avatar asked Jan 09 '19 08:01

Alif Al-Gibran


People also ask

How do you divide two numbers in Kotlin?

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 .

How do you get a remainder in Kotlin?

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.


Video Answer


2 Answers

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.

like image 97
Yoni Gibbs Avatar answered Sep 19 '22 20:09

Yoni Gibbs


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

like image 42
Derrick Avatar answered Sep 21 '22 20:09

Derrick