Rounding a number (double) to specific decimal places

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • surpsi
    New Member
    • Mar 2014
    • 1

    Rounding a number (double) to specific decimal places

    Hey guys I want a little help of yours. I am writing a program and I want to restrict its answer to a certain decimal places. (two decimal places) Her is my program,
    Code:
    /* To create a bank application capable of finding an interest */
    class bank
    {
        public void enter ( double principal , double rate_of_interest , double time )
        {
            double SI = (principal * rate_of_interest * time) / (100.0);
            double A = principal + SI;
            double CItemp1 = (1+ (rate_of_interest/100.0));
            double CItemp2 = Math.pow( CItemp1 , time);
            double CItemp3 = principal * CItemp2;
            double CI = CItemp3 - principal;
            System.out.println("The amount obtained after calculating simple interest is " + A);
            System.out.println("The Simple Interest for the required sum is Rs " + SI);
            System.out.println("The amount obtained after calculating compound interest is " + CItemp3);
            System.out.println("The Compound Interest for the required sum is Rs " + CI);
            
        }
    }
    Last edited by Rabbit; Mar 13 '14, 03:26 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    Hi surpsi and welcome to bytes.com!

    I guess you're trying to format the output, correct? If so, take a look at the string formatting syntax; this will allow you to set various aspects of your output, including the precision of an output. And such formats are accepted by PrintStream#pri ntf(...), which is exactly what System.out.prin tf(...) is.

    Comment

    • chaarmann
      Recognized Expert Contributor
      • Nov 2007
      • 785

      #3
      If this is a bank application, you should never calculate with float or double, because you will get significant rounding problems. Just use BigDecimal class instead.

      If the problem is very simple to solve (that means there is only adding, subtracting, and multiplying of whole numbers), then just convert the price to an integer and always calculate with that. Only during output, you would add the needed decimal point.
      Example 3 Euro and 21 cent should not be stored as "double price=3.21", but as "int price=321", that means calculate always in cent instead of euro. At the end, if you want to output the Euros without the cents, don't divide by 100 because of rounding problems. Just convert the whole number to a string and cut off the last two characters.

      By the way, just read about rounding problems, especially calculations with the number "0.10", which cannot be converted to an exact binary representation.

      Comment

      Working...