Format negative amount of USD with a minus sign, not brackets (Java)

前端 未结 7 1480
离开以前
离开以前 2020-12-03 09:49

How do I get NumberFormat.getCurrencyInstance() to print negative USD currency values with a minus sign?

7条回答
  •  隐瞒了意图╮
    2020-12-03 10:16

    It requires a little tweaking of the DecimalFormat returned by NumberFormat.getCurrencyInstance() to do it in a locale-independent manner. Here's what I did (tested on Android):

    DecimalFormat formatter = (DecimalFormat)NumberFormat.getCurrencyInstance();
    String symbol = formatter.getCurrency().getSymbol();
    formatter.setNegativePrefix(symbol+"-"); // or "-"+symbol if that's what you need
    formatter.setNegativeSuffix("");
    

    IIRC, Currency.getSymbol() may not return a value for all locales for all systems, but it should work for the major ones (and I think it has a reasonable fallback on its own, so you shouldn't have to do anything)

提交回复
热议问题