【问题标题】:Converting TextView value to double variable将 TextView 值转换为双变量
【发布时间】:2014-10-24 11:38:18
【问题描述】:

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

textPrice.setText(String.format(priceFormat, item.getPrice()));

现在我想将它转换为一个双变量,我绝对认为我必须使用 priceFormat 但我不知道如何使用。这个底线是错误的。

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

【问题讨论】:

    标签: android


    【解决方案1】:

    您需要将 textPrice.getText() 转换为 String,因为它的 Double.parseDouble(String):

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

    您还必须消除 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");
    }
    

    【讨论】:

      【解决方案2】:

      你需要在解析之前删除那个S$,方法之一是:

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

      【讨论】:

        猜你喜欢
        • 2011-08-25
        • 2019-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-12
        • 1970-01-01
        相关资源
        最近更新 更多