删除不需要的小数点".0&" [英] Drop un-needed decimal ".0"

查看:140
本文介绍了删除不需要的小数点".0&"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的计算器,但它在显示要成为整数的小数点时出现问题.例如,如果输入的表达式是"50 + 50",则返回"0".答案将是"100.0&".我知道发生这种情况是因为我的输出被设置为double,但是我无法弄清楚如何仅在答案为".0&"时才能将这些数字转换为整数.

I'm making a simple calculator and I am having an issue with it showing a decimal on what I want to just be a whole number. For example, if the entered expression is "50 + 50" the answer will come out "100.0". I understand that it's happening because my output is set as a double, but I can't figure out how to convert those numbers to integer only when the answer is ".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
}

推荐答案

您可以使用

You can use removeSuffix:

fun main() {
    println(100.5.toString().removeSuffix(".0"))
    println(100.0.toString().removeSuffix(".0"))
}

输出:

100.5
100

这篇关于删除不需要的小数点".0&"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆