Daniel2233
Daniel2233

Reputation: 41

Can't Parse a double from user input Kotlin

I'm trying to learn and create a basic sales tax app (inputs from item price and tax). In order to do this, I need to use a float or double for the decimals. I am very new to kotlin and don't know much, so I do not understand how I can get my num1 to parseDouble, I can clearly do it with the Integer data type with no errors. I've also tried toDouble which is giving me errors. Any help would be appreciated, thank you!

val calcButton = findViewById<Button>(R.id.calcButton)
calcButton.setOnClickListener {
   var textPrice: EditText = findViewById(R.id.textPrice)
   var textTax:   EditText = findViewById(R.id.textTax)
   var textTotal: EditText = findViewById(R.id.textTotal)

   // error here: "Unresolved reference: parseDouble"
   var num1 = Double.parseDouble(textTax.getText().toString());
   // "parseInt" is working, however
   var num2 = Integer.parseInt(textTax.getText().toString());
}

Upvotes: 1

Views: 1247

Answers (1)

smac89
smac89

Reputation: 43078

Try:

textTax.getText().toString().toDouble();

The reason you can't use Double.parseDouble is because Double in kotlin is not exactly the same as Double in Java, therefore, just calling Double will call kotlin's version, which doesn't have parseDouble static method.

If you want to use the Double from java.lang, you must specify the full package name:

java.lang.Double.parseDouble(textTax.getText().toString());

Or you can also do:

import java.lang.Double.*;
parseDouble(textTax.getText().toString());

I would suggest just sticking with Kotlin's versions, as they usually result in shorter code.

Upvotes: 4

Related Questions