因此,我正在编写一个进行财务计算的程序。但是,由于我对数据类型使用了double,因此美分未四舍五入。这是源代码:
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75 / 100 / 12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths)) / (Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
System.out.println("Principle: $" + principle);
System.out.println("Annual Rate: " + annualRate + "%");
System.out.println("Number of years: " + numYears);
System.out.println("Monthly Payment: $" + monthlyPayment);
System.out.println("Total Payments: $" + totalPayment);
System.out.println("Total Interest: $" + totalInterest);
}
}
我的教练也不希望它使用DecimalFormat类。我当时想通过执行以下操作来获取美分值:variable-Math.floor(variable),然后将其四舍五入到最接近的百分之一,然后将其相加。
最佳答案
不使用为此目的而存在的(通常将使用的)JDK提供的库类,用于算术舍入的伪代码为:
乘以100,就可以得到美分
加(或减,如果数字为负)0.5,因此下一步舍入到最接近的美分
强制转换为int
,它会截断小数部分
除以100天,就可以得到美元)
现在去写一些代码。