0

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?

  • 1
    Fyi, this has nothing to do with overflows, which is something completely different. This is caused by floating point arithmetic: https://en.wikipedia.org/wiki/Floating-point_arithmetic – somethingsomething May 03 '22 at 12:22
  • [This question](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) is very relevant. – gidds May 03 '22 at 19:25

1 Answers1

0

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")
}
Yunus D
  • 998
  • 6
  • 13
  • reminder, this will only take care of first digit after the decimal point if you want more precision use more # like "#.######" – Yunus D May 03 '22 at 12:24