0

Im doing a Loan Calculator for class. I'm nearly done but the only thing missing is how to round INTEREST_RATE instead of $298.95833333333337 i would like to get $298.96. But i don't know how.

Enter your old Principle = 25000
Enter your current payment = 450

Previous Balance: $25000.0
Payment: $450.0
Interest Paid: $151.04166666666666
Principle Paid: $298.95833333333337
New Principal: $24701.041666666668

import java.util.Scanner; 

public class LoanCalculator {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    /**
     * Declaration Section  
     * 
     */
    Scanner keyboard = new Scanner(System.in); 
    double INTEREST_RATE; 
    double currentPayment;
    double oldPrincipal;
    double interestPaid;
    double principalPaid;
    double newPrincipal; 


    /**
     * Process Section
     * 
     */

    System.out.println("Enter your old Principle = ");
    oldPrincipal = keyboard.nextDouble(); 

    System.out.println("Enter your current payment = ");
    currentPayment = keyboard.nextDouble();  

    INTEREST_RATE = 7.25 / 100.0; //fix this 

    interestPaid = oldPrincipal * INTEREST_RATE / 12;

    principalPaid = currentPayment - interestPaid; 

    newPrincipal = oldPrincipal - principalPaid; 


    /**
     * Output Section
     * 
     * */
    System.out.println("Previous Balance: " + "$"+ oldPrincipal);
    System.out.println("Payment: " + "$"+ currentPayment);
    System.out.println("Interest Paid: " + "$"+ interestPaid);
    System.out.println("Principle Paid: " + "$"+ principalPaid);
    System.out.println("New Principal: " + "$"+ newPrincipal); 


}//Main()

}//LoanCalculator
Daco Apps
  • 23
  • 5
  • possible duplicate of [round double to two decimal places in java](http://stackoverflow.com/questions/5710394/round-double-to-two-decimal-places-in-java) – blacktide Sep 26 '14 at 20:37
  • I want to round to the nearest penny, and in my class so far we haven't learned about BigDecimal – Daco Apps Sep 26 '14 at 20:40
  • @DacoApps Did you look at the question identified by cxdm that your own question duplicates? BigDecimal may not make an appreciable difference in your case, since this appears to be schoolwork. You should work on your Search Fu. You can save everyone (including yourself) a lot of time by making at least some effort to search for an answer on your own. – MarsAtomic Sep 26 '14 at 20:47
  • @MarsAtomic i have ive looked everywhere and what csdm posted doesnt help. Im new in Java and i dont know how to use a BigDecimal. Im not that far in my course yet. – Daco Apps Sep 26 '14 at 20:51
  • 1
    How about [`DecimalFormat`](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html)? That was also mentioned in the answers there. – Lone nebula Sep 26 '14 at 20:52
  • @DacoApps Did you bother to google it? 2nd result is an extensive tutorial on how to use it, specifically with money: http://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorial – tnw Sep 26 '14 at 20:53

4 Answers4

3

Never use double for financial calculations! It's really dangerous.

From the Java language specification:

float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Use BigDecimal, it also have the rounding functionalities that you're looking for.

Community
  • 1
  • 1
Alboz
  • 1,833
  • 20
  • 29
1

BigDecimal

Never use the floating-point types (float, Float, double, Double) for matters such as money where accuracy is important. Floating-point trades away accuracy for speed-of-execution. Instead use the slow but accurate class BigDecimal.

Choose your mode of rounding. I chose “Banker’s rounding”.

Covered already in Stack Overflow many times. So search for more info. Briefly here is some code to get you started. I have not run this code.

BigDecimal interestPecentage = 
    new BigDecimal( "7.25" )
    .setScale( 2 , RoundingMode.HALF_EVEN )    // Round using Banker’s rounding.
;   

BigDecimal interestRateAnnual = 
    interestPecentage.divide(                 // Divide percentage by 100 to get an interest rate as a decimal fraction.
        new BigDecimal( "100" ) 
    )
    .setScale( 2 , RoundingMode.HALF_EVEN )
; 
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Use this Method is perfect and secure

only transform the value to String and the result to Double or Float

public String PerfectRound(String number, int limit){
//        System.out.println(numero);
        String t="";int c=0,e=number.length();
        do {            
            try {
                if(String.valueOf(number.charAt(c)).equals(".")){if(limit==0){break;}e=c+limit+1;}
                t=t+number.charAt(c);
            } catch (Exception je) {
                t=t+"0";
            }
            c++;
//            System.out.println(t);
        } while (c<e);
//        System.out.println(t);
        return t;
    }

Example:

double a=23.32313232;
a=Double.valueOf(PerfectRound(a+"", 2));
System.out.println(a);
WearFox
  • 293
  • 2
  • 19
-3

Edit: we should use BigDecimal class for financial calculation. BigDecimal class has built-in formatter so I add it.

Edit: changed the rounding mode to half even as @Basil Bourque suggested.

      public class LoanCalculator {public static void main(String[] args) {
   Scanner keyboard = new Scanner(System.in);
    BigDecimal INTEREST_RATE, currentPayment, oldPrincipal, interestPaid, principalPaid, newPrincipal, month;
    System.out.println("Enter your old Principle = ");
    oldPrincipal = keyboard.nextBigDecimal();
    System.out.println("Enter your current payment = ");
    currentPayment = keyboard.nextBigDecimal();
    NumberFormat formatter = new DecimalFormat("#0.00");
    INTEREST_RATE = new BigDecimal(7.25 / 100.0);
    formatter.format(INTEREST_RATE);//only format
    month = new BigDecimal(12);
    interestPaid = INTEREST_RATE.multiply(oldPrincipal);
    interestPaid = interestPaid.divide(month, 2);
    principalPaid = currentPayment.subtract(interestPaid);
    newPrincipal = oldPrincipal.subtract(principalPaid);
    System.out.println("Previous Balance: " + "$" + oldPrincipal);
    System.out.println("Payment: " + "$" + currentPayment);
    System.out.println("Interest Paid: " + "$" + interestPaid.setScale(2, RoundingMode.HALF_EVEN)
            + " $" + formatter.format(interestPaid));
    System.out.println("Principle Paid: " + "$" + principalPaid.setScale(2, RoundingMode.HALF_EVEN)
            + " $" + formatter.format(principalPaid));
    System.out.println("New Principal: " + "$" + newPrincipal.setScale(2, RoundingMode.HALF_EVEN)
            + " $" + formatter.format(newPrincipal));}}
Mohannd
  • 1,288
  • 21
  • 20
  • 6
    Downvoted because using doubles for financial calculations is the sort of thing that gets people thrown in jail. – o11c Sep 26 '14 at 21:12
  • 1
    You're taking a Student into the dark side of the force :). Even @Jon Skeet can't do financial calculations using float or double. – Alboz Sep 27 '14 at 08:03
  • I don't know why keep down voting. the answer is edited from years....! – Mohannd Dec 23 '19 at 11:48