BattleDrum
BattleDrum

Reputation: 818

Negative number instead of positive

The At the end of executing this code, I expect 0.00, but I get -0.00. This code calculates the price of bond based on the market rate, determines if it is offered at a premium or discount then calculates.

The part I am concerned with is determining the balance in the premium account. In calculating this I use -= on the variable premium_bal2.

Here's the code :

 package totalbeginner.demo;

 import java.text.NumberFormat;
 import java.util.Locale;

 import javax.swing.*;

 public class TotalBeginner{

public static void main(String[] args){

    System.out.println("We are offering a $100,000 bond at 10% par for 3 years");
    double price; //price of bond determined from rates

    double market_rate = Double.parseDouble(JOptionPane.showInputDialog("What is the market rate?"));

    NumberFormat formatter= NumberFormat.getCurrencyInstance(Locale.UK);
    int year=1;//year


    double premium_bal=0;;//premium balance
    double premium_bal2=0;


    if(market_rate<10){//premium bond offer
         price = (0.10*100000*5.5673)+(100000*0.5565);
         premium_bal= price-100000;//premium bal
         premium_bal2 = price-100000;//premium bal

         System.out.println("Cash dr. "+formatter.format(price));
         System.out.println("Premium dr. "+formatter.format(price-100000));
         System.out.println("Bonds Payable cr. "+ formatter.format(100000));// issue journal entry



        while(year<3){
        System.out.println("Interest dr. "+formatter.format(10000));//interest payment
        System.out.println("Cash cr. "+formatter.format(10000));

        //write-off

        System.out.println("Interest dr. "+formatter.format(premium_bal/3));
        System.out.println("Premium cr. "+formatter.format(premium_bal/3));
        premium_bal2-=premium_bal/3; 


        if (year==2){
            System.out.println("Interest dr. "+formatter.format(10000));//interest payment
            System.out.println("Cash cr. "+formatter.format(10000));

            System.out.println("Cash cr. "+formatter.format(100000));//Bond retirement 
            System.out.println("Bonds Payable dr. "+formatter.format(100000));

            //write-off

            System.out.println("Interest dr. "+formatter.format(premium_bal/3));
            System.out.println("Premium dr. "+formatter.format(premium_bal/3));


            //Amount in balance account
            premium_bal2-=premium_bal/3;
            System.out.println("Amount in premium account: "+formatter.format(premium_bal2));

                }
        //counter year
        year++;

        }
    }
  System.exit(0);
   }        
 }

Upvotes: 1

Views: 75

Answers (1)

leeyuiwah
leeyuiwah

Reputation: 7152

Use BigDecimal (or int or long, with a scaling factor) instead of Double or double, the latter are for floating point numbers and are only approximations.

Upvotes: 1

Related Questions