在java中舍入而不使用任何特殊函数或格式
我有一个课堂项目,我的老师希望我对我的数字使用type double,但要求我不要使用特殊的函数或格式,因为roudning等于最接近的美元 以下是我目前掌握的情况:在java中舍入而不使用任何特殊函数或格式,java,math,rounding,currency,Java,Math,Rounding,Currency,我有一个课堂项目,我的老师希望我对我的数字使用type double,但要求我不要使用特殊的函数或格式,因为roudning等于最接近的美元 以下是我目前掌握的情况: //Variable Declarations String name; int hoursWorked; double hourlyPayRate; double federalTaxRate; double stateTaxRate; double grossPay; d
//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
我需要将联邦税、州税、扣除总额和净工资等方面的输出四舍五入到最接近的便士,因为这些都是美元金额。不使用库函数,将正的
双精度
四舍五入到最接近的int
的最简单方法是:
static int round(double d) {
return (int)(d + .5);
}
这是因为将浮点数强制转换为int将截断该数字的非整数部分。您需要知道的是小数点后第千位的数字。我得到的方法是首先将小数点移动到要舍入的位置。(移动=网付*100) 接下来,你需要去掉小数点后的所有内容。我会利用类型转换。(千分之一=移位-(整数)移位) 然后你有一个简单的if语句,知道是向上取整还是向下取整。四舍五入为(网付=网付-(千分之一/100)) 加起来是(网付=网付+((千分之一)/100)
我希望这能有所帮助。您的老师希望您编写自己的舍入方法吗?那么您的老师希望您使用什么?什么构成“特殊函数”?愚蠢的作业,真的不是这么愚蠢的作业。我只告诉你怎么做,因为这是作业,你必须自己编程。你首先要找到点的左右部分,所以反复把你的数字除以10,直到它小于0。现在你有了小数部分。如果小数部分>=0.5,你就可以给你的数字加1,然后减去小数部分,否则你就减去小数部分。