Android 将TextView值转换为双变量

Android 将TextView值转换为双变量,android,Android,在前面,我将文本设置为这样,priceFormat为S$%.2f textPrice.setText(String.format(priceFormat, item.getPrice())); 现在我想把它转换成一个双变量,我肯定认为我必须使用priceFormat,但我不知道如何使用它。这个底线是错误的 double Price=Double.parseDouble(textPrice.getText()); 您需要在解析之前删除该S$,方法之一是: String text=textPri

在前面,我将文本设置为这样,priceFormat为S$%.2f

textPrice.setText(String.format(priceFormat, item.getPrice()));
现在我想把它转换成一个双变量,我肯定认为我必须使用priceFormat,但我不知道如何使用它。这个底线是错误的

double Price=Double.parseDouble(textPrice.getText());

您需要在解析之前删除该
S$
,方法之一是:

String text=textPrice.getText();
字符串priceText=text.split($”[1]。trim()//使用货币字符拆分数字字符
double priceVal=double.parseDouble(priceText)//将其解析为双精度

您需要将textPrice.getText()转换为字符串,因为它是Double.parseDouble(字符串):

您还必须消除S$和尾随符号:

double price = Double.parseDouble(mStatus.getText().toString().replaceAll("S\\$|\\.$", ""));
当然,您应该减少这种错误:

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");
}
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");
}