简体   繁体   English

实时数据<string>浮动解析替换</string>

[英]LiveData<String>To Float Parse Replace

I'm using the Google purchase library and I'm using the price via a LiveData.我正在使用 Google 购买库,并通过 LiveData 使用价格。 Price tag: It looks like $20.99.价格标签:看起来像 20.99 美元。 I have to parse this data and print only 20.99.我必须解析这些数据并只打印 20.99。 For this, I think I need to convert the LiveData String data to float or integer.为此,我想我需要将 LiveData String 数据转换为浮点数或 integer。 How can I do that?我怎样才能做到这一点?

static public class SkuDetails {
    final public String sku;
    final public LiveData<String> title;
    final public LiveData<String> description;
    final public LiveData<String> price;
    final public int iconDrawableId;

    SkuDetails(@NonNull String sku, TrivialDriveRepository tdr) {
        this.sku = sku;
        title = tdr.getSkuTitle(sku);
        description = tdr.getSkuDescription(sku);
        price = tdr.getSkuPrice(sku);
        iconDrawableId = skuToResourceIdMap.get(sku);
    }
}

BillingClient;计费客户端;

public final LiveData<String> getSkuPrice(String sku) {
    LiveData<SkuDetails> skuDetailsLiveData = skuDetailsLiveDataMap.get(sku);
    assert skuDetailsLiveData != null;
    return Transformations.map(skuDetailsLiveData, SkuDetails::getPrice);
}

EDIT: Sorry, I forgot to add the line of code that prints the price information correctly.编辑:对不起,我忘了添加正确打印价格信息的代码行。 I have shared the code I need to parse below.我在下面分享了我需要解析的代码。

public LiveData<String> getSkuPrice(Subscription var1) {
    return getSkuDetails(var1.getSku()).price;
}

Activity.xml;活动.xml;

android:text="@{viewModel.getSkuPrice(subscription)}"

You can do it something like this once you've price LiveData assigned.一旦您为 LiveData 分配了price ,您就可以这样做。

// get the string value from "price" LiveData
        String strPrice = price.getValue();

        //remove dollar sign from this price
        String priceWithoutDollarSign = strPrice.replaceAll("[^\\d.]", "");

        //convert/parse it as float just in-case needed otherwise priceWithoutDollarSign will be enough
        float resultPrice = Float.parseFloat(priceWithoutDollarSign);

Sorry, I forgot to add the line of code that prints the price information correctly.抱歉,我忘了添加正确打印价格信息的代码行。 I have shared the code I need to parse below.我在下面分享了我需要解析的代码。

public LiveData<String> getSkuPrice(Subscription var1) {
    return getSkuDetails(var1.getSku()).price;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM