How to properly display a price up to two decimals (cents) including trailing zeros in Java?

后端 未结 5 1434
小蘑菇
小蘑菇 2021-02-09 14:42

There is a good question on rounding decimals in Java here. But I was wondering how can I include the trailing zeros to display prices in my program like: $1.50, $1.00

T

5条回答
  •  [愿得一人]
    2021-02-09 15:28

    It can probably be done with String.format(...), but you could use DecimalFormat:

    double price = 2.50000000000003;
    DecimalFormat formatter = new DecimalFormat("$0.00");
    System.out.println(formatter.format(price)); // print: $2.50
    

提交回复
热议问题