Java税收四舍五入到小数位数

时间:2015-02-07 06:40:12

标签: java

餐费总额(餐费加税和小费)

公共课程菜单{

public static void main(String[] args) 
{
    double burgers; 
    double soda; 
    double meal;
    double tax = 0.0825;
    double taxAmount;
    double totalWithTax;
    double tipRate = 0.15;
    double tipAmount;
    double totalBill;

    //charge and tax 

    burgers = 5 * 6.95;
    soda = 4 * 1.75;
    meal = burgers + soda;
    taxAmount = meal*tax;
    totalWithTax = meal + tax;
    tipAmount = totalWithTax * tipRate;
    totalBill = meal + taxAmount + tipAmount;


    System.out.println("Total meal charge $ "+ meal);
    System.out.println("Tax amount "+ taxAmount);
    System.out.println("Tip amount " + tipAmount);
    System.out.println("Total bill " + totalBill);
}

}

输出:

总餐费$ 41.75

税额3.444375< ===我需要截断为3.44

提示金额6.274875000000001< ===我需要将其截断为6.78

总账单51.46925

3 个答案:

答案 0 :(得分:0)

而不是

System.out.println("Tax amount "+ (int) (tax_amount * 100) /100);//100/100 doesnt makes sense here and you need decimal number so dont typecast to int which will remove the decimal part.

使用

System.out.printf("Tax amount %.2f", tax_amount / 100.0);

在OP的编辑问题之后:

更改这些:

System.out.println("Total meal charge $ "+ meal);
System.out.println("Tax amount "+ taxAmount);
System.out.println("Tip amount " + tipAmount);
System.out.println("Total bill " + totalBill);

要:

 System.out.printf("Total meal charge $ %.2f\n", meal);
 System.out.printf("Tax amount %.2f\n", taxAmount);
 System.out.printf("Tip amount %.2f\n", tipAmount);
 System.out.printf("Total bill %.2f\n", totalBill);

输出是:

Total meal charge $ 41.75 
Tax amount 3.44 
Tip amount 6.27 
Total bill 51.47 

答案 1 :(得分:0)

使用双重格式。你可以将你的双打四舍五入到你需要的任何地方,在这种情况下为2。

double taxAmmount;
double tipAmount;
double totalBill;

DecimalFormat dFormat = new DecimalFormat("#.##");

//get the tax ammount
taxAmount = meal*tax;

//round to two decimal places.
taxAmmount = Double.parseDouble(dFormat(taxAmmount));

//for the tipAmmount and totalBill do the same thing.
//do caclulations for each.
//then format.
tipAmmount = Double.parseDouble(dFormat(tipAmmount));
totalBill = Double.parseDouble(dFormat(totalBill));

答案 2 :(得分:0)

我不推荐这些类型的计算使用双打,除非你是100%最新的他们可以做什么和不能做什么,并希望跳过很多箍以确保你的计算不会去吧,使用BigDecimals要容易得多。检查EJP对此问题的回答:https://stackoverflow.com/a/12684082/144578

或者对于好的(非现场)阅读,请检查http://floating-point-gui.de/