代码之家  ›  专栏  ›  技术社区  ›  suleydaman

我怎样才能让数字格式使用一种货币,但要用小数分/便士?

  •  0
  • suleydaman  · 技术社区  · 8 年前

    我想用 NumberFormat 转换 Double String .我正在使用 数字格式 基于货币区域设置,但这会使 到小数点后2位。我怎么能让它不把货币整圆,这样它就包含了零头硬币呢?

    所以如果我有

    val doubleFormatMoney = 1.032323135
    
    val format = NumberFormat.getCurrencyInstance(Locale.US)
    
    val stringFormatMoney = format.format(doubleFormatMoney)
    

    那么我们应该 stringFormatMoney = $1.032323135 但是我得到了 stringFormatMoney = $1.03

    1 回复  |  直到 8 年前
        1
  •  2
  •   Rich    8 年前

    每个地区的货币格式规范包括要使用的小数位数,因为小数位数随货币而异(有些货币使用3dp,例如约旦第纳尔)。因此 NumberFormat.getCurrencyInstance(Locale.US) 包括按定义舍入到2dp。

    如果你想使用标准 Double toString 加上区域设置的货币符号,您可以执行以下操作:

    Currency.getInstance(Locale.US).getSymbol(Locale.US) + doubleFormatMoney
    

    参见 How to get the currency symbol for particular country using locale?