Java - format double value as dollar amount

前端 未结 5 843
故里飘歌
故里飘歌 2020-12-01 14:03

I need to format the double \"amt\" as a dollar amount println(\"$\" + dollars + \".\" + cents) such that there are two digits after the decimal.

What is the best wa

相关标签:
5条回答
  • 2020-12-01 14:21

    Use NumberFormat.getCurrencyInstance():

    double amt = 123.456;    
    
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    System.out.println(formatter.format(amt));
    

    Output:

    $123.46
    
    0 讨论(0)
  • 2020-12-01 14:23

    You can use a DecimalFormat

    DecimalFormat df = new DecimalFormat("0.00");
    System.out.println(df.format(amt));
    

    That will give you a print out with always 2dp.

    But really, you should be using BigDecimal for money, because of floating point issues

    0 讨论(0)
  • 2020-12-01 14:27

    Use DecimalFormat to print a decimal value in desired format e.g.

    DecimalFormat dFormat = new DecimalFormat("#.00");
    System.out.println("$" + dFormat.format(amt));
    

    If you wish to display $ amount in US number format than try:

    DecimalFormat dFormat = new DecimalFormat("####,###,###.00");
    System.out.println("$" + dFormat.format(amt));
    

    Using .00, it always prints two decimal points irrespective of their presence. If you want to print decimal only when they are present then use .## in the format string.

    0 讨论(0)
  • 2020-12-01 14:37

    You can use printf for a one liner

    System.out.printf("The original balance is $%.2f.%n", cardBalance);
    

    This will always print two decimal places, rounding as required.

    0 讨论(0)
  • 2020-12-01 14:43

    Use BigDecimal instead of double for currency types. In Java Puzzlers book we see:

    System.out.println(2.00 - 1.10);
    

    and you can see it will not be 0.9.

    String.format() has patterns for formatting numbers.

    0 讨论(0)
提交回复
热议问题