我试图找到一种正确的方法来使用正确的逗号、空格、点其他分隔符位置来本地化价格,并将货币代码设置在正确的位置作为后缀或前缀。我也想使用负数。
我发现了什么?
我正在尝试谷歌并尝试每个解决方案,最简单的方法是:
private val format: DecimalFormat = NumberFormat.getCurrencyInstance(globalLocale) as DecimalFormat
fun format(amount: Double, currencyCode: String): String {
format.currency = Currency.getInstance(currencyCode)
return format.format(amount)
}
其中 globalLocale
是 Locale.getDefault()
-> 手机的区域设置。
问题出在负数上,由于某些原因,它需要括号并调用 format(-10.00, "EUR")
返回 (EUR10.00)
我找到了一个解决方案,应用模式:
format.applyPattern("$#,##0.00;-$#,##0.00")
但这种硬编码会阻止货币符号位置和空格/逗号/点本地化。
如何达到这个结果?
- 传递
amount
和currencyCode
并获得正确的本地化
价格(不带任何负数括号)?
编辑 看来这个问题只存在于 Locale.US 中,所以问题是如何在 US 语言环境中避免这个括号?
最佳答案
object Currency {
fun format(num: Double, currency: String, maxFractionDigits: Int?): String {
val format = NumberFormat.getCurrencyInstance(Locale.getDefault())
format.maximumFractionDigits = maxFractionDigits ?: 0
val cFormat = Currency.getInstance(currency)
format.currency = cFormat
return format.format(num)
}
}
val amountStr = Currency.format(
budgetAllocationModel.used ?: 0.0,
budgetAllocationModel.currency ?: "USD", 0
)
Currency 是一个对象,我使用 Local.getDefault() 来转换货币以获取货币的本地字符串。
amountStr 是使用该对象的示例
关于java - 使用货币代码解析(本地化)价格的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56643874/