将货币更改为货币格式

问题描述 投票:0回答:1

我具有以下构建货币格式器的方法。有两个输入字段,区域设置和货币:

    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)

[当货币输入与语言环境输入的货币相同时,它可以正常工作,因此:

  • [区域设置:es_ES,货币:EUR = 0,00€->确定
  • [区域设置:en_US,货币:USD = $ 0.00->确定

但是如果我们有以下错误,那就是错误的:

  • 区域设置:es_ES,货币:USD = 0,00 $-> KO
  • 语言环境:en_US,货币:EUR = $ 0.00-> KO

似乎货币没有正确设置...知道吗?我做错了吗?

kotlin currency number-formatting decimalformat currency-formatting
1个回答
1
投票

这似乎是由于以下原因:

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
}
© www.soinside.com 2019 - 2024. All rights reserved.