【问题标题】:Change the currency to a currency formatter将货币更改为货币格式化程序
【发布时间】:2019-10-21 15:05:34
【问题描述】:

我有以下方法来构建货币格式化程序。有 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)

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

  • 语言环境:es_ES,货币:EUR = 0,00 € -> OK
  • 语言环境:en_US,货币:USD = $ 0.00 -> OK

但如果我们有以下情况,那就错了:

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

似乎货币设置不正确......有什么想法吗?我做错了什么?

【问题讨论】:

    标签: kotlin currency number-formatting decimalformat currency-formatting


    【解决方案1】:

    这似乎是由于这一行:

    currencyFormat.positivePrefix = currencyFormat.positivePrefix + " "
    

    此时的正前缀取决于所传递语言环境的货币。例如,如果您以getCurrencyDecimalFormat(Locale.US, Currency.getInstance("EUR")) 的形式调用您的方法,那么此时您的currencyFormat 将绑定到美元(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
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 2015-10-24
      • 2016-05-03
      • 1970-01-01
      • 2016-04-25
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多