如何在java中舍入到两个小数位

时间:2015-02-05 06:30:36

标签: java

最后双倍YearDep = 0.15; //这是每年一辆汽车失去之前的价值

     double HybridDepreciation= HybridCarCost * Math.pow(1-YearDep,5);
     double HybridFuelCost=(Miles*5*GasCost)/HybridCarMPG;

     double GasPowerDepreciation=GasPowerCost * Math.pow(1-YearDep,5);
     double GasPowerFuelCost=(Miles *5*GasCost)/GasPowerMPG;

     double HybridTotalCost=HybridCarCost - HybridDepreciation + HybridFuelCost;
     double GasPowerTotalCost= GasPowerCost - GasPowerDepreciation + GasPowerFuelCost;

     System.out.printf("The total cost for the " + HybridName + " " + "is" +" $"+ HybridTotalCost);

     System.out.println();
     System.out.printf("The total cost for the " + GasPowerName + " "+ "is" + " $"+ GasPowerTotalCost);

4 个答案:

答案 0 :(得分:1)

使用DecimalFormat

DecimalFormat df = new DecimalFormat(".00");
System.out.printf("The total cost for the " + HybridName + " " + "is" +" $"+ df.format(HybridTotalCost));
 System.out.println();
 System.out.printf("The total cost for the " + GasPowerName + " "+ "is" + " $"+ df.format(GasPowerTotalCost));

或者您可以使用

String.format("The total cost for the  %s is $%.2f", HybridName ,HybridTotalCost)

答案 1 :(得分:0)

 double roundOff = Math.round(a*100)/100.0;

 DecimalFormat number = new DecimalFormat("#.00");
 number.format(new Double(2223.8990))

答案 2 :(得分:0)

DecimalFormat df = new DecimalFormat("#.00"); 

然后

df.format(<your_value>);

或者

System.out.println( String.format( "%.2f", <your_value> ) );

答案 3 :(得分:0)

你可以使用。

double roundOff1 = (double) Math.round(HybridTotalCost);
double roundOff2 = (double) Math.round(GasPowerTotalCost);

你也可以使用。

DecimalFormat df = new DecimalFormat("###.##");
System.out.printf("The total cost for the " + HybridName + " " + "is" +" $"+ df.format(HybridTotalCost));
System.out.println();
System.out.printf("The total cost for the " + GasPowerName + " "+ "is" + " $"+df.format(GasPowerTotalCost));