负数而不是正数

时间:2016-12-27 02:20:12

标签: java formatting double

在执行此代码的最后,我期望0.00,但我得到-0.00。 该代码根据市场价格计算债券价格,并确定 如果是以溢价或折扣提供,则计算。

我关注的部分是确定保费的余额 帐户。在计算这个时,我在变量premium_bal2上使用 - =。

以下是代码:

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

1 个答案:

答案 0 :(得分:1)

使用BigDecimal(或intlong,使用缩放系数)代替Doubledouble,后者用于浮点数和只是近似值。