need space between currency symbol and amount

Viewed 8997

I'm trying to print INR format currency like this:

NumberFormat fmt = NumberFormat.getCurrencyInstance();
fmt.setCurrency(Currency.getInstance("INR"));
fmt.format(30382.50);

shows Rs30,382.50, but in India its written as Rs. 30,382.50(see http://www.flipkart.com/) how to solve without hardcoding for INR?

6 Answers

Sorry for Kotlin I came here from android). As I understood there is no correct solutions for that, so that's why my solution is also hack)

fun formatBalance(
    amount: Float,
    currencyCode: String,
    languageLocale: Locale
): String {

amount can be String as well.

    val currencyFormatter: NumberFormat = NumberFormat.getCurrencyInstance(languageLocale)
    currencyFormatter.currency = Currency.getInstance(currencyCode)
    val formatted = currencyFormatter.format(amount)

formatted will get amount with currency from correct side but without space. (Example: 100$, €100)

    val amountFirstSymbol = amount.toString()[0]
    val formattedFirstSymbol = formatted[0]

    val currencySymbolIsBefore = amountFirstSymbol != formattedFirstSymbol

Then I use this little hack to understand if currency symbol is before amount. So for example amount is 100 then amountFirstSymbol will be "1". And if formatted is 100$ then formattedFirstSymbol also will be "1". That means we can put our currency symbol behind amount but now with space.

    val symbol = currencyFormatter.currency?.symbol
    return if (currencySymbolIsBefore) "$symbol $amount"
    else "$amount $symbol"
Related