我有一个班级项目,我的老师要我使用double类型作为我的号码,但是当roudning达到最接近的美元时,我需要使用和特殊功能或格式化。
这是我到目前为止所拥有的:
//Variable Declarations
String name;
int hoursWorked;
double hourlyPayRate;
double federalTaxRate;
double stateTaxRate;
double grossPay;
double netPay;
double totalDeduction;
//Getting user inputs
Scanner input = new Scanner(System.in);
System.out.print("Enter employee's name: ");
name = input.next();
System.out.print("Enter number of hours worked in a week: ");
hoursWorked = input.nextInt();
System.out.print("Enter hourly pay rate: ");
hourlyPayRate = input.nextDouble();
System.out.print("Enter federal tax withholding rate: ");
federalTaxRate = input.nextDouble();
System.out.print("Enter state tax withholding rate: ");
stateTaxRate = input.nextDouble();
System.out.println();
//Amount Calculations
grossPay = hoursWorked * hourlyPayRate;
totalDeduction = (grossPay * federalTaxRate) +
(grossPay * stateTaxRate);
//Printing Payroll Statement
System.out.println("Employee Name: " + name);
System.out.println("Hours Worked: " + hoursWorked);
System.out.println("Pay Rate: $" + hourlyPayRate);
System.out.println("Gross Pay: $" + grossPay);
System.out.println("Deductions: ");
System.out.println("\tFederal Withholding (" + (federalTaxRate * 100) +
"%): $" + (grossPay * federalTaxRate));
System.out.println("\tState Withholding (" + (stateTaxRate * 100) +
"%): $" + (grossPay * stateTaxRate));
System.out.println("\tTotal Deduction: $" + totalDeduction);
System.out.println("Net pay: $" + (grossPay - totalDeduction));
我的输出与此类似:
Enter employee's name: Bob
Enter number of hours worked in a week: 25
Enter hourly pay rate: 10.30
Enter federal tax withholding rate: .2
Enter state tax withholding rate: .09
Employee Name: Bob
Hours Worked: 25
Pay Rate: $10.3
Gross Pay: $257.5
Deductions:
Federal Withholding (20.0%): $51.5
State Withholding (9.0%): $23.175
Total Deduction: $74.675
Net pay: $182.825
我需要联邦托管,国家托管,总扣除和净工资等产出四舍五入到最近的便士,因为这些都是美元金额。
答案 0 :(得分:0)
在不使用库函数的情况下将正double
舍入到最近的int
的最简单方法是:
static int round(double d) {
return (int)(d + .5);
}
这是有效的,因为将一个浮点数转换为int
会截断数字的非整数部分。
答案 1 :(得分:0)
您需要知道的是小数位数千分之一的数字。我得到的方法是先将小数点移动到你想要舍入的位置。 (shift = netPay * 100)
接下来你需要摆脱小数点左边的一切。我会利用类型铸造。 (千分之一=移位 - (整数)移位)
然后你有一个简单的if语句来知道是向上舍入还是向下舍入。四舍五入(netPay = netPay - (千分之一/ 100))
对它进行整理(netPay = netPay +((千分之一)/ 100)
我希望这会有所帮助。