【问题标题】:Kotlin calculator can't remove double .0 in the end [duplicate]Kotlin 计算器最终无法删除双 .0 [重复]
【发布时间】:2020-11-10 17:50:36
【问题描述】:
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()
        }

    }

以 double 形式获取输出不是一种选择,因为它最终会给出 Integers .0。我尝试添加无效的.roundToInt(),编译时出现以下错误:Type mismatch: inferred type is Int but Double was expected

【问题讨论】:

  • 使用NumberFormat 格式化数字。 toString() 通常用于调试目的。
  • 在这种事情上使用双打可能会产生一些尴尬的极端情况。我强烈怀疑使用 BigDecimals 会更好;使用它们,您可以获得所需的准确性,而无需进行巧妙的舍入来隐藏不准确性。您可以根据需要设置它们的比例以给出尽可能多或尽可能少的小数位。

标签: kotlin


【解决方案1】:

如果我理解正确,您想去掉双精度值末尾的十进制零(尾随零)。如果是这样,这是一个干净的解决方案。 用双精度值进行所有计算,当你想打印结果时,这样做:

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

如果它们是零或其他十进制值,这将消除十进制数字(它不会对您的数字进行四舍五入,只是对其进行格式化)

【讨论】:

    【解决方案2】:

    我尝试添加无效的 .roundToInt(),编译时出现以下错误:类型不匹配:推断类型为 Int 但预期为 Double。

    你只是在错误的地方做,使用

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

    等等。

    【讨论】:

      猜你喜欢
      • 2021-03-30
      • 2013-03-14
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      相关资源
      最近更新 更多