问题
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.
回答1:
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));
回答2:
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
}
}
回答3:
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
}
来源:https://stackoverflow.com/questions/47949902/get-currency-symbol-of-only-one-character-e-g-%e2%82%b9-etc-locale-doesnt-matter