Home > Software engineering >  Starts comparing from the first number, not the whole number in kotlin
Starts comparing from the first number, not the whole number in kotlin

Time:09-24

Hello I need to compare 2 numbers and I used >, => but it doesn't compare whole number, it looks for the leftest(left) number and compare for example the number is 92,236 and i want to compare it with 100,000, it says 92236 is bigger than 100,000 and it is because of the first number which is 9 and the first number of second number that is 1 so it says 100,000 is not bigger than 9236

here what I had done

class 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 است. ادامه میدهید؟")

THANKS FOR HELPING ME :)

CodePudding user response:

You are most likely comparing strings (text) and not numbers here. That's why it's using the alphabetical order instead of the integer order:

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

You probably want to convert your strings into integers instead:

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

Note that toInt will crash if the strings are not actual numbers (for instance empty).

You can use toIntOrNull if you want more safety. It returns null if the string is not a number, so you can simply check for null and deal with this problem separately before comparing.

  • Related