Skip to content Skip to sidebar Skip to footer

Converting Textview Value To Double Variable

In front I set the text like that with the priceFormat being S$%.2f. textPrice.setText(String.format(priceFormat, item.getPrice())); Now I want to convert it to a double variable

Solution 1:

You need to convert the textPrice.getText() to a String since its Double.parseDouble(String):

double price = Double.parseDouble(mStatus.getText().toString());

You also have to eliminate the S$ and the trailing .:

double price = Double.parseDouble(mStatus.getText().toString().replaceAll("S\\$|\\.$", ""));

Of course you should make this less error-prone:

double price = 0d;
try {
    price = Double.parseDouble(mStatus.getText().toString().replaceAll("S\\$|\\.$", ""));
}
catch (NumberFormatException e) {
    // show an error message to the user
    textPrice.setError("Please enter a valid number");
}

Solution 2:

you need to remove that S$ before parsing, one of the way is:

Stringtext= textPrice.getText();
StringpriceText= text.split("$")[1].trim(); //splitting numeric characters with the currency charactersdoublepriceVal= Double.parseDouble(priceText); //parsing it to double

Post a Comment for "Converting Textview Value To Double Variable"