【问题标题】:Starts comparing from the first number, not the whole number in kotlin从第一个数字开始比较,而不是 kotlin 中的整数
【发布时间】:2021-11-17 01:05:51
【问题描述】:

您好,我需要比较 2 个数字,我使用了 >, => 但它不比较整数,它会查找最左边(左)的数字并进行比较 例如,数字是 92,236,我想将它与 100,000 进行比较,它说 92236 大于 100,000,这是因为第一个数字是 9,而第二个数字的第一个数字是 1,所以它说 100,000 不大大于 9236

我做了什么

类IncreaseMoneyFragment : Fragment() {

var decide = ""

val increaseEditText = mIncreaseMoneyBinding.increaseEdt.text.toString()  (get value of edit text)
                        val currentPayment = it.payment  (get loanPayment from database)
                        if (increaseEditText > currentPayment) {
                            Toast.makeText(activity, "more", Toast.LENGTH_SHORT).show()
                            val more = "بیشتر"
                            decide = more
                        } else {
                            Toast.makeText(activity, "less", Toast.LENGTH_SHORT).show()
                            val less = "کمتر"
                            decide = less
                        }
                        builder.setTitle(" مبلغ مورد نظر از مبلغ قسط وام $decide است. ادامه میدهید؟")

感谢您的帮助:)

【问题讨论】:

    标签: android sorting kotlin compare


    【解决方案1】:

    您很可能在这里比较字符串(文本)而不是数字。这就是为什么它使用字母顺序而不是整数顺序:

    println("92236" > "100000") // true
    println(92236 > 100000) // false
    

    您可能希望将字符串转换为整数:

    if (increaseEditText.toInt() > currentPayment.toInt()) {
        // ...
    }
    

    请注意,如果字符串不是实际数字(例如为空),toInt 将崩溃。

    如果您想要更安全,可以使用toIntOrNull。如果字符串不是数字,则返回null,因此您可以简单地检查null并在比较之前单独处理此问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      相关资源
      最近更新 更多