将货币更改为货币格式化程序

Change the currency to a currency formatter

我有以下方法来构建货币格式化程序。有 2 个输入字段,语言环境和货币:

    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 绑定到美元(并且 currencyFormat.positivePrefix 导致 $)。

将此行进一步向下移动,在设置格式符号下方。但是TBH我什至不确定你为什么需要它。在货币符号后有一个 space 应该是区域设置相关的而不是硬编码的。

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
}