Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin gives wrong result when multipliyng

I want to multiply 281.65 by 100 and get 28165, I execute:

fun main(args: Array<String>) {
    println("${281.65 * 100}")
}

but I get 28164.999999999996 Whats the problem here and how do I get 28165 as a result? Is there a good Kotlin way to work with that?

like image 957
Rainmaker Avatar asked Oct 25 '25 00:10

Rainmaker


1 Answers

Yep, it's floating point math issue.

kotlin.math package has roundToLong extension function which helps in this case.

(281.65 * 100).roundToLong()
like image 168
Rainmaker Avatar answered Oct 27 '25 21:10

Rainmaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!