删除不需要的小数“.0”
Drop un-needed decimal ".0"
我正在制作一个简单的计算器,但我在显示小数点时遇到了问题,我只想将其作为整数。例如,如果输入的表达式是“50 + 50”,答案将是“100.0”。我知道这是因为我的输出设置为双精度,但我无法弄清楚如何仅在答案为“.0”时将这些数字转换为整数。
我的输出答案代码:
fun equal (view: View) {
secondnum = editText.text.toString()
decpressed = 0
var sum = 0.0
when (op) {
"+" -> {sum = (firstnum.toDouble() + secondnum.toDouble())}
"-" -> {sum = (firstnum.toDouble() - secondnum.toDouble())}
"*" -> {sum = (firstnum.toDouble() * secondnum.toDouble())}
"/" -> {sum = (firstnum.toDouble() / secondnum.toDouble())}
}
editText.setText(sum.toString())
textView.text = "$firstnum $op $secondnum ="
zero = true
}
您可以使用 removeSuffix
:
fun main() {
println(100.5.toString().removeSuffix(".0"))
println(100.0.toString().removeSuffix(".0"))
}
输出:
100.5
100
我正在制作一个简单的计算器,但我在显示小数点时遇到了问题,我只想将其作为整数。例如,如果输入的表达式是“50 + 50”,答案将是“100.0”。我知道这是因为我的输出设置为双精度,但我无法弄清楚如何仅在答案为“.0”时将这些数字转换为整数。
我的输出答案代码:
fun equal (view: View) {
secondnum = editText.text.toString()
decpressed = 0
var sum = 0.0
when (op) {
"+" -> {sum = (firstnum.toDouble() + secondnum.toDouble())}
"-" -> {sum = (firstnum.toDouble() - secondnum.toDouble())}
"*" -> {sum = (firstnum.toDouble() * secondnum.toDouble())}
"/" -> {sum = (firstnum.toDouble() / secondnum.toDouble())}
}
editText.setText(sum.toString())
textView.text = "$firstnum $op $secondnum ="
zero = true
}
您可以使用 removeSuffix
:
fun main() {
println(100.5.toString().removeSuffix(".0"))
println(100.0.toString().removeSuffix(".0"))
}
输出:
100.5
100