如何使用 DecimalFormatSymbols 和货币格式化 double?

How to format double with DecimalFormatSymbols and currency?

我的结果应该是这样的:$100 00,99 我设法根据需要格式化数字,但没有货币。 我设法分别获得了货币,但无法将两者结合在一起。 对于编号格式,我在 .

的答案中使用了 DecimalFormatSymbol
 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)
}

如何将两者结合起来?

希望对您有所帮助。

    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