【问题标题】:How to format double with DecimalFormatSymbols and currency?如何使用 DecimalFormatSymbols 和货币格式化双精度?
【发布时间】:2020-02-11 12:37:40
【问题描述】:

我的结果应该是这样的:$100 00,99 我设法根据需要格式化数字,但没有货币。 我设法单独获得货币,但无法将两者放在一起。 对于编号格式,我使用了DecimalFormatSymbol,就像对question 的回答一样。

 private fun formatValue(value: Double, formatString: String): String {
     val formatSymbols = DecimalFormatSymbols(Locale.ENGLISH)
     formatSymbols.decimalSeparator = ','
     formatSymbols.groupingSeparator = ' '
     val formatter = DecimalFormat(formatString, formatSymbols)
     return formatter.format(value)
 }

 formatValue(amount ,"###,###.00")

对于我使用此代码的货币:

fun getFormattedCurrency(currency: String, amount: Double): String {
     val c = Currency.getInstance(currency)
     val nf = NumberFormat.getCurrencyInstance()
     nf.currency = c
     return  nf.format(amount)
}

如何将两者结合起来?

【问题讨论】:

  • 如果你只是在末尾添加货币符号会不会更简单?如果您在某些 TextView 中显示金额,只需执行 myTextView.text = currency + amount.toString() 之类的操作
  • 别忘了货币是由 Locale 格式化的

标签: android formatting double decimal currency


【解决方案1】:

希望对你有所帮助。

    val decimalFormatSymbols = DecimalFormatSymbols().apply {
        decimalSeparator = ','
        groupingSeparator = ' '
        setCurrency(Currency.getInstance("AED"))
    }


    val decimalFormat = DecimalFormat("$ #,###.00", decimalFormatSymbols)
    val text = decimalFormat.format(2333222)
    println(text) //$ 2 333 222,00


    val decimalFormat2 = DecimalFormat("¤ #,###.00", decimalFormatSymbols)
    val text2 = decimalFormat2.format(2333222)
    println(text2) //AED 2 333 222.00

请注意,如果您使用 ¤ 而不是特定的货币符号(如 $,€),它将根据您创建的货币实例使用符号。您还可以从文档中获取更多信息。 https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

您还可以在以下位置找到 ISO 4217 代码 https://en.wikipedia.org/wiki/ISO_4217

【讨论】:

  • 谢谢!几乎就在那里... text2 没有逗号作为分隔符,尽管 text 有。在文档中看到这个:currency sign; replaced by currency symbol; if doubled, replaced by international currency symbol; if present in a pattern, the monetary decimal separator is used instead of the decimal separator. 无论如何要绕过它?
  • 很高兴听到它有帮助:)
猜你喜欢
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 2013-03-17
  • 2013-10-18
  • 2011-09-16
相关资源
最近更新 更多