将双倍转换为2个小数位

时间:2016-03-29 07:19:09

标签: java

我有一个代码,其中一个人在每个杯子中​​订购一定数量的咖啡和咖啡镜头,并且该程序计算总价格(purchasePrice)。但是,当我将购买价格输出为双倍时,它只输出一个小数点后1位的数字。如何将其更改为输出2位小数。

double purchasePrice = 0;
  for (counting = 0; counting < coffeeCups; counting++) {
    System.out.println("Cup " + (counting + 1) + " has " + coffeeShots[counting] + " shot(s) and will cost $" + (2 + coffeeShots[counting]) + "\n");
    purchasePrice+= 2 + (coffeeShots[counting]);
  }
  System.out.println(coffeeCups + " coffees to purchase.");
  System.out.println("\nPurchase price is $" + purchasePrice + ".");

1 个答案:

答案 0 :(得分:1)

请参阅Decimal Format

// 2 places of decimal
DecimalFormat formatter = new DecimalFormat( "#.00" );

System.out.println(formatter.format(1.23));    // 1.23
System.out.println(formatter.format(1));       // 1.00
System.out.println(formatter.format(1.234));   // 1.23