Search code examples
android-studiokotlinnumberformatexceptionparseint

java.lang.NumberFormatException: For input string: "16000$" in kotlin


I want to make display show "16000$" before click increase btn or decrease btn. when I make code like this error caused by :java.lang.NumberFormatException: For input string: "16000$ . but I should display $. Lets check my code and help me plz.


  var productprice = findViewById<TextView>(R.id.productPrice)
        productprice.text= intent.getStringExtra("price")+"$"
        var price = productPrice.text.toString().toInt()
        var inc_val= price
        var getPrice = price

        decrease.isEnabled=false

        increase.setOnClickListener {
            increaseInteger()
            getPrice+= inc_val
            productprice.text=getPrice.toString()+"$"
        }

        decrease.setOnClickListener {
            decreaseInteger()
            getPrice -= inc_val
            productprice.text=getPrice.toString()+"$"
        }


Solution

  • var price = productPrice.text.toString().toInt() - you try to convert "16000$" to Int here. Please get substring here first.

    Formally, right code is:

    val priceText = productPrice.text.toString()
    val price = priceText.substring(0, priceText.length - 1).toInt()
    

    However really I advice you to store value internally. You price is part of model. E.g. you can avoid text parsing and just read value from model. E.g. code will be like this:

    var price = intent.getIntExtra("price") // we store int value here, not String
    var inc_val= price
    decrease.isEnabled=false
    displayPrice()
    
    increase.setOnClickListener {
        intent.setIntExtra(intent.getIntExtra("price") + inc_val) // read, update, save
        displayPrice()
    }
    decrease.setOnClickListener {
        intent.setIntExtra(intent.getIntExtra("price") - inc_val) // read, update, save
        displayPrice()
    }
    
    
    /*this function just shows price*/
    fun displayPrice() {
       val price = intent.getIntExtra("price")
    
       productprice.text= "$price\$"
    }