gpt4 book ai didi

java - 寻找一种保留两位小数而不四舍五入的方法

转载 作者:行者123 更新时间:2023-12-02 03:48:50 25 4
gpt4 key购买 nike

我必须以两位小数显示我的输出,程序输出每月付款应为 205.16,总付款应为 12309.91。在使用小数格式对正确的答案进行四舍五入之前,但在四舍五入到小数点后两位之后,输出现在为高 0.01。如何删除多余的小数位而不向上舍入 0.01?

import javax.swing.*;
import java.text.*;


/**
*DriverMortgageClass
*/

public class DriverMortgageClass
{
public double annualInterestRate;
public int numberOfYears;
public double loanAmount;
public double monthlyPayment;
public double totalPayment;
public double monthlyInterestRate;

DecimalFormat fmt = new DecimalFormat ("0.00");

//main method
public static void main(String[] args) {
new DriverMortgageClass().start();
}

//declare private mortgage object
private Mortgage mortgage;

public DriverMortgageClass()

{
mortgage = new Mortgage();
}
public void start()
{

//get input for interest rate
String annualInterestRateString = JOptionPane.showInputDialog(null,"Enter yearly interest rate, for example 8.5",JOptionPane.QUESTION_MESSAGE);
annualInterestRate=Double.parseDouble(annualInterestRateString);
mortgage.setAnnualInterestRate(annualInterestRate);


//get input for number of years
String numberOfYearsString = JOptionPane.showInputDialog(null,"Enter number of years as an integer, for example 5",JOptionPane.QUESTION_MESSAGE);
numberOfYears= Integer.parseInt(numberOfYearsString);
mortgage.setNumberOfYears(numberOfYears);


//set loan amount
String loanAmountString = JOptionPane.showInputDialog(null,"Enter loan amount, for example 10000.00",JOptionPane.QUESTION_MESSAGE);
loanAmount= Double.parseDouble(loanAmountString);
mortgage.setLoanAmount(loanAmount);


//Invoke monthly and total payment
monthlyInterestRate=annualInterestRate/1200;
monthlyPayment=loanAmount*monthlyInterestRate /(1-(Math.pow(1/(1+monthlyInterestRate),numberOfYears*12)));
totalPayment=monthlyPayment*numberOfYears*12;

//display monthly and total payment
JOptionPane.showMessageDialog(null,"The monthly payment is"+ " " + fmt.format(monthlyPayment)+'\n'
+"The total payment is"+ " " + fmt.format(totalPayment));

System.exit(0);
}
}

最佳答案

使用DecimalFormat .

DecimalFormatt df = new DecimalFormat( "#.00" );
df.format(1.478569); // 1.48

不希望四舍五入吗?

double c = 1.478569d;
c = (double)((long)(c*100))/100; // 1.47

双重转换方式可能会溢出[ Jonny Henly如下所述]。谨防。 :)

有很多种方法可以做到这一点。或者,

df = new DecimalFormat( "#.000" );
String num = df.format(1.478569);
num = num.substring(0, num.length()-1); // 1.47

有帮助吗?

关于java - 寻找一种保留两位小数而不四舍五入的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com