【发布时间】: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