首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >‘'discount’函数不能正常工作

‘'discount’函数不能正常工作
EN

Stack Overflow用户
提问于 2019-10-12 23:10:28
回答 1查看 168关注 0票数 0

我有一个discount函数,它接受一个‘netPrice’参数(一个double),并在我的类中更新一个私有变量rate(也是一个double)以降低价格。计算似乎是可行的,但有一个问题;它会产生不准确的结果。

代码语言:javascript
运行
复制
public class Good{
  private String name;
  private double netPrice;

  final static double VAT_RATE = 0.2;

  /**
   * The constructor instantiates an object representing a priced good.
   * @param name
   * @param netPrice
   */
  public Good(String name, double netPrice){
      this.name = name;
      this.netPrice = netPrice;
  }

  /**
   * Retrieves and reads the value of name.
   * @return the name of the good.
   */
  public String getName(){
      return name;
  }

  /**
   * Updates the value name.
   * @param name
   */
  public void setName(String name){
      this.name = name;
  } 

  /**
   * Retrieves and reads the value of netPrice
   * @return the net price of the good.
   */
  public double getNetPrice(){
      return netPrice;
  }

  /**
   * Updates the value netPrice
   * @param netPrice
   */
  public void setNetPrice(double netPrice){
      this.netPrice = netPrice;
  }

  /**
   * @return netprice adjusted for VAT
   */
  public double grossPrice(){
      return netPrice + (netPrice * VAT_RATE);
  }

  public void discount(double rate){
      double discount = (netPrice/100) * rate;
      netPrice = netPrice - discount;
  }
  /**
   * @return formatted string stating the name and the gross price of the good.
   */
  public String toString(){
      return "This " + name + " has a gross price of \u00A3 " + grossPrice();
  }

  public static void main(String[] args){
      Good milk = new Good("milk", 0.50);

      System.out.println(milk);
      milk.discount(20);
      System.out.println(milk); 
  }
} 

在上面的例子中,我期望折扣价格是£ 0.48,但我得到的是£ 0.48000000000000004。我不知道为什么会关闭,所以如果有人能解释为什么会发生这样的事情,那就太好了。

至于修复,我最初认为我可以通过使用以下方法四舍五入到2d.p.来绕过这个问题:

代码语言:javascript
运行
复制
public void discount(double rate){
        double discount = (netPrice/100) * rate;
        netPrice = netPrice - discount;
        netPrice = Math.round(netPrice * 100.0) / 100.0

然而,这似乎不起作用,实际上它给了我与上面相同的答案。另一个修复可能涉及使用BigDecimal,但我不知道如何才能在不将netPrice变量更改为不同类型的情况下干净利落地工作(这是我不想做的事情)。有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2019-10-13 01:45:28

金融用途Bigdecimal

阅读这篇文章

java-performance.info/bigdecimal-vs-double-in-financial-calculations/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58355512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档