user4092957
user4092957

Reputation:

How to round to the nearest cent in Java

So I am writing a program that does some financial calculations. However, because I used double for my data types, the cents are not rounded. Here is the source code:

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);
    }
}

My instructor also does not want this to use the DecimalFormat class. I was thinking to obtain the cents value by doing: variable-Math.floor(variable), and then rounding that amount to the nearest hundredth, then adding that together.

Upvotes: 0

Views: 6532

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48693

Well, if you cannot use the DecimalFormat class, you could use printf():

TextLab03, Student Version

Principle       : $259,000.00
Annual Rate     : 5.75%
Number of years : 30.00
Monthly Payment : $1,511.45
Total Payments  : $544,123.33
Total Interest  : $285,123.33
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;

        printAmount("Principle", principle);
        printPercent("Annual Rate", annualRate);
        printCount("Number of years", numYears);
        printAmount("Monthly Payment", monthlyPayment);
        printAmount("Total Payments", totalPayment);
        printAmount("Total Interest", totalInterest);
    }

    public static void printPercent(String label, double percentage) {
        //System.out.printf("%-16s: %,.2f%%%n", label, percentage);
        printNumber(label, percentage, "", "%", 16);
    }

    public static void printCount(String label, double count) {
        //System.out.printf("%-16s: %,.2f%n", label, count);
        printNumber(label, count, "", "", 16);
    }

    public static void printAmount(String label, double amount) {
        //System.out.printf("%-16s: $%,.2f%n", label, amount);
        printNumber(label, amount, "$", "", 16);
    }

    public static void printNumber(String label, double value, String prefix, String suffix, int labelWidth) {
        String format = String.format("%%-%ds: %%s%%,.2f%%s%%n", labelWidth);
        System.out.printf(format, label, prefix, value, suffix);
    }
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 425238

Without using the JDK-provided library classes that exist for this purpose (and would normally be used), the pseudocode for rounding arithmetically is:

  • multiply by 100, giving you cents
  • add (or subtract if the number is negative) 0.5, so the next step rounds to the nearest cent
  • cast to int, which truncates the decimal part
  • divide by 100d, giving you dollars)

Now go write some code.

Upvotes: 3

Related Questions