【问题标题】:Negative number instead of positive负数而不是正数
【发布时间】:2016-12-27 02:20:11
【问题描述】:

在执行此代码结束时,我期望 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);
   }        
 }

【问题讨论】:

  • 您不应该使用浮点类型来表示货币。
  • 只是为了确定,premium_bal2 总是大于premium_bal/3 吗?仅供参考,双 0.00-0.00 实际上 数学上 说是相同但二进制表示不同,这是计算机的限制(一般)。无论如何,有些人试图用一些tricks 删除那个负号,而不是干预数字本身.. -- what you need to know about floating point

标签: java formatting double


【解决方案1】:

使用BigDecimal(或intlong,带有比例因子)代替Doubledouble,后者用于浮点数并且只是近似值。

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2012-05-12
    相关资源
    最近更新 更多