Search code examples
kotlindouble

how to mitigate overflow in Kotlin


Like to title suggest, I was writing operation functions in Kotlin when I encountered overflows. Here is an Example:

fun main(args: Array<String>) {
    val x: Double = 2.2
    val y: Double = 1.0

    val z = x - y

    println("$x - $y is  $z")
}

the output will be

2.2 - 1.0 is  1.2000000000000002

instead of

2.2 - 1.0 is  1.2

The functions I'm writing require double datatype variables but I keep encountering these overflows. How do I mitigate this issue?


Solution

  • You can use DecimalFormat

    import java.text.DecimalFormat
    
    fun main(args: Array<String>) {
        val x: Double = 2.2
        val y: Double = 1.0
    
        val df = DecimalFormat("#.#")
        val z = df.format((x - y)).toDouble()
    
        println("$x - $y is  $z")
    }