寻找一种方法来保持两个小数位而不会四舍五入

时间:2016-03-18 01:17:58

标签: java decimal

我必须以小数点后两位显示输出,每月付款的节目输出应为205.16,总付款应为12309.91。在使用十进制格式将答案舍入到正确之前但在舍入到两位小数之后,输出现在为.01到高。如果不进行四舍五入,我该怎么做才能删除多余的小数位.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);
    }
}

1 个答案:

答案 0 :(得分:1)

使用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

有帮助吗?