TimWeb
TimWeb

Reputation: 405

How to get currency symbol from Play Billing Library

I use Play Billing Library and I have two subscriptions for one and three months. For a 3 month subscription, I want to display the price for 1 month. For example, a 1 month subscription is $1,50 and a 3 month subscription is $3 ($1 for a 1 month). But I have some problems with currencies.

This is a code:

long priceAmountMicros = skuDetails.getPriceAmountMicros(); //3000000
String priceCurrency = skuDetails.getPriceCurrencyCode(); //USD

float priceFloat = (float)priceAmountMicros / 3 / 1000000; //1
String price = new DecimalFormat("#0.00").format(priceFloat);

Currency currency = Currency.getInstance(priceCurrency);
String symbolCurrency = currency.getSymbol();//$

textView.setText(price + " " + symbolCurrency); //1.00 $ or 70.00 руб

The code almost is working. USD converted to $. EUR converted to £ and others. There are some problems with some currencies, for example, the Russian currency does not work. RUB converted to руб, but I expect

There is a standard method for getting the price:

String price = skuDetails.getPrice();//3 $ or 210 ₽

Am I doing something wrong? Could you help me please?

Upvotes: 10

Views: 3286

Answers (4)

Jazib Khan
Jazib Khan

Reputation: 460

Use this function to get the monthly price for an annual subscription. Don't use java currency class as it has issues with some currencies.

private fun getAnnualMonthlyPrice(skuDetails: SkuDetails): String {
    val re = Regex("[0-9.,]")
    val currency = re.replace(skuDetails.price, "")
    val priceMicro = skuDetails.priceAmountMicros / (1_000_000f * 12f)
    return "${currency}${"%.2f".format(priceMicro)}"
}

Upvotes: 0

ikbal
ikbal

Reputation: 1894

You can use Currency class from java.util package

Currency.getInstance(sku.priceCurrencyCode).symbol

will give you the symbol for currency code

Upvotes: 8

Ahmed Amin Shahin
Ahmed Amin Shahin

Reputation: 1143

getOriginalPrice() - returns the original price with additional currency formatting.

Upvotes: 0

Martin Zeitler
Martin Zeitler

Reputation: 76807

One cannot assume that the currency symbol always would be to the left of the price.

Simply strip all numbers and decimal separators:

String symbol = skuDetails.getPrice().replaceAll("[\\d.,]", "");

However, the most easy might be:

textView.setText(skuDetails.getPrice());

I mean, why you even need the currency symbol?

Upvotes: 0

Related Questions