How to use Java's DecimalFormat for “smart” currency formatting?

前端 未结 10 659
旧巷少年郎
旧巷少年郎 2021-01-01 09:34

I\'d like to use Java\'s DecimalFormat to format doubles like so:

#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41

Th

10条回答
  •  长情又很酷
    2021-01-01 10:27

    Does it have to use DecimalFormat?

    If not, it looks like the following should work:

    String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
    //Handle the weird exception of formatting whole dollar amounts with no decimal
    currencyString = currencyString.replaceAll("\\.00", "");
    

提交回复
热议问题