Home > OS >  LiveData<String>To Float Parse Replace
LiveData<String>To Float Parse Replace

Time:02-06

I'm using the Google purchase library and I'm using the price via a LiveData. Price tag: It looks like $20.99. I have to parse this data and print only 20.99. For this, I think I need to convert the LiveData String data to float or 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);
}

CodePudding user response:

You can do it something like this once you've price LiveData assigned.

// 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);

CodePudding user response:

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;
}
  •  Tags:  
  • Related