Home > OS >  How to input a decimal number in a textEdit
How to input a decimal number in a textEdit

Time:12-25

I have a TextEdit that has the input type of numberDecimal and I executes some code with inputted number

when I enter a whole number it works fine but when I enter a number with a decimal point the app completely restarts

So how would I make it work with a decimal number?

if you do end up helping me thank you in advanced

KT file

    class f_to_c : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.f_to_c)

        val actionBar = supportActionBar

        val calculate = findViewById<Button>(R.id.calculate)
        val tempEntered = findViewById<TextView>(R.id.tempEntered)
        val result = findViewById<TextView>(R.id.result)
        val temp = findViewById<EditText>(R.id.temp)


        if (actionBar != null){
            actionBar.title = "Fahrenheit To Celsius"
            actionBar.setDisplayHomeAsUpEnabled(true)
        }

        calculate.setOnClickListener {
            var x = Integer.parseInt(temp.getText().toString()).toString().toInt()
            tempEntered.text = x.toDouble().toString()
            result.text = ((x-32).toFloat()*5/9).toString()
        }

    }
}

CodePudding user response:

If you want to handle decimal numbers, you shouldn't use Integer.parseInt. That will throw an error on something like "1.23". The following should work (or you could use Double.parseDouble)

val x = temp.getText().toString().toDoubleOrNull() ?: 0.0
tempEntered.text = x.toString()
result.text = ((x-32.0)*5.0/9.0).toString()

You may want to handle the null case differently in case the user enters an invalid number like "1..3", but this would just default to 0 in that case instead of throwing.

Also, if this is to be used internationally, you should consider that some locales use a comma for a decimal separator ("1,23") - which will break here. You could either use a locale-aware number parser for that, or just replace commas with periods before converting.

val xs = temp.getText().toString().replace(",",".")
val x = xs.toDoubleOrNull() ?: 0.0
  • Related