Home > Net >  Wrong comparing of Double and Int numbers in Kotlin
Wrong comparing of Double and Int numbers in Kotlin

Time:04-23

I'm working on calculator project but when I tried to use two similar ways of comparing double and int numbers I got different results. So my question is Why are these ways of comparing works differently?

//some code that parse the string
//...
//code of calculating:

fun calculateIn(queueNumbers: Queue<Double>, queueActions: Queue<Char>) {
var action: Char
var result = queueNumbers.poll()
var operand: Double

while (!queueNumbers.isEmpty()) {
    operand = queueNumbers.poll()
    action = queueActions.poll()
    when (action) {
        '-' -> result -= operand
        ' ' -> result  = operand
        '*' -> result *= operand
        '/' -> result /= operand
        '%' -> result = result % operand * -1.0
    }
  }
  var pointNum = 8.3

  println("pointNum = "   pointNum)
  println(if(pointNum.compareTo(pointNum.toInt()) == 0) pointNum.toInt() else pointNum)

  println("result = "   result)
  println(if(result.compareTo(result.toInt()) == 0) result.toInt() else result)
}

Result of code:

"10.3   -2" //input String

[10.3, -2.0] //queueNumbers

[ ]//queueActions

pointNum = 8.3

8.3

result = 8.3

8

I think that is strange because if I run similar code I will get the correct result:

var pointNum = 8.3

println(if(pointNum.compareTo(pointNum.toInt()) == 0) pointNum.toInt() else pointNum)

So there is result of this code:

8.3

Full code on GitHub: enter image description here

  • Related