0
fun equalsClick(view: View) {
        val sec0perandText: String = resultTextView.text.toString()
        var sec0perand: Double = 0.0.roundToInt()

        if (!TextUtils.isEmpty(sec0perandText)) {
            sec0perand = sec0perandText.toDouble()

        }

        when (operation) {
            "+" -> resultTextView.text = (operand + sec0perand).toString()
            "-" -> resultTextView.text = (operand - sec0perand).toString()
            "*" -> resultTextView.text = (operand * sec0perand).toString()
            "/" -> resultTextView.text = (operand / sec0perand).toString()
        }

    }

Getting output in double is not an option because it gives Integers .0 in the end. I tried adding .roundToInt() which didn't work, when compiled it gives following error: Type mismatch: inferred type is Int but Double was expected.

  • Use `NumberFormat` to format the number. `toString()` is meant for debugging purposes usually. – Nicolas Nov 10 '20 at 18:34
  • Using Doubles for this sort of thing is likely to give some awkward corner cases.  I strongly suspect you'll be better off with BigDecimals instead; with them, you get the accuracy you want, without having to do dodgy rounding to hide inaccuracies.  And you can set their scale to give as many or as few decimal places as you need. – gidds Nov 11 '20 at 00:03

2 Answers2

2

If I have understood correctly, you wanna get rid of the decimal zeros at the end of a double value (trailing zeros). If so, here is a clean solution. Do all your calculations with double values and when you wanna print the result, do it this way:

resultTextView.text = String.format("%.0f", operand + sec0perand)

this will get rid of the decimal digits if they are zeros or other decimal values (it does not round your number just formats it)

MehranB
  • 1,460
  • 2
  • 7
  • 17
1

I tried adding .roundToInt() which didn't work, when compiled it gives following error: Type mismatch: inferred type is Int but Double was expected.

You are just doing it in the wrong place, use

resultTextView.text = (operand + sec0perand).roundToInt().toString()

and so on.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487