Reputation: 2607
i have currency code (e.g. USD,INR,etc...). I want to get symbols of only one letter of those codes (e.g $,₹, etc). i have tried to find many solutions like this but it doesn't works for me. i am using code as below
var pound = Currency.getInstance("GBP");
var symbol = pound.getSymbol();
but it returns symbols like (Rs., US$, AU$, etc...). i want to get only one character symbol as mentioned above. i know that symbols are dependent on their locale but i want to get symbols independent from their locale.
Upvotes: 3
Views: 3723
Reputation: 617
To answer your question quickly in Kotlin:
var pound = Currency.getInstance("GBP");
val symbol = pound.symbol
println(symbol) // prints £
In case useful, I paste my solution to get currency code (i.e.: EUR) and currency symbol (i.e. €) and :
val locale = Locale.getDefault()
val numberFormat = NumberFormat.getCurrencyInstance(locale)
println(numberFormat.currency) // on my device in Italy prints: EUR
val symbol = numberFormat.currency?.symbol
println(symbol) // on my device in Italy prints: €
Upvotes: 1
Reputation: 31
I simply created this kotlin extension function which isolates the currency symbol if there is one or uses the provided symbol if there isn't one.
// Supply the Currency Symbol, e.g. US$, would return $ and IDR would return IDR
fun String.isolateCurrencySymbol(): String{
for (char in this){
if (char !in CharRange('A', 'Z')){
return char.toString()
}
}
return this
}
Upvotes: 0
Reputation: 9
This works fine for me
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
count()
}
fun count () {
val pound = Currency.getInstance("USD")
var str:String
str = if(Build.VERSION.SDK_INT >=24) pound.getSymbol(Locale.getDefault(Locale.Category.DISPLAY))
else pound.getSymbol(resources.configuration.locale)
tvText.text = str
}
}
Upvotes: 0
Reputation: 3100
try to calling default Locale
in getSymbol() like getSymbol(Locale.getDefault(Locale.Category.DISPLAY))
check below code
Currency pound = Currency.getInstance("GBP");
pound.getSymbol(Locale.getDefault(Locale.Category.DISPLAY));
Upvotes: 3