我具有以下构建货币格式器的方法。有两个输入字段,区域设置和货币:
private fun getCurrencyDecimalFormat(locale: Locale, currency: Currency): DecimalFormat {
val currencyFormat = NumberFormat.getCurrencyInstance(locale) as DecimalFormat
currencyFormat.positivePrefix = currencyFormat.positivePrefix + " "
currencyFormat.roundingMode = RoundingMode.DOWN
val symbol = currency.getSymbol(locale)
val decimalFormatSymbols = currencyFormat.decimalFormatSymbols
decimalFormatSymbols.currencySymbol = symbol
currencyFormat.decimalFormatSymbols = decimalFormatSymbols
currencyFormat.isParseBigDecimal = true
return currencyFormat
}
它被这样称呼:
val currencyFormat = getCurrencyDecimalFormat(locale, currency)
return currencyFormat.format(amount)
[当货币输入与语言环境输入的货币相同时,它可以正常工作,因此:
但是如果我们有以下错误,那就是错误的:
似乎货币没有正确设置...知道吗?我做错了吗?
这似乎是由于以下原因:
currencyFormat.positivePrefix = currencyFormat.positivePrefix + " "
此时的正前缀取决于所传递语言环境的货币。例如,如果您将您的方法调用为getCurrencyDecimalFormat(Locale.US, Currency.getInstance("EUR"))
,则此时currencyFormat
绑定到USD(currencyFormat.positivePrefix
产生$
)。
在设置格式符号的下方,将该行进一步向下移动。但是TBH我什至不知道为什么需要它。货币符号后有空格应取决于语言环境,而不应进行硬编码。
fun getCurrencyDecimalFormat(locale: Locale, currency: Currency): DecimalFormat {
val currencyFormat = NumberFormat.getCurrencyInstance(locale) as DecimalFormat
currencyFormat.roundingMode = RoundingMode.DOWN
val symbol = currency.getSymbol(locale)
val decimalFormatSymbols = currencyFormat.decimalFormatSymbols
decimalFormatSymbols.currencySymbol = symbol
currencyFormat.decimalFormatSymbols = decimalFormatSymbols
currencyFormat.isParseBigDecimal = true
currencyFormat.positivePrefix = currencyFormat.positivePrefix + " "
return currencyFormat
}