我有一个discount
函数,它接受一个‘netPrice
’参数(一个double),并在我的类中更新一个私有变量rate(也是一个double)以降低价格。计算似乎是可行的,但有一个问题;它会产生不准确的结果。
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.来绕过这个问题:
public void discount(double rate){
double discount = (netPrice/100) * rate;
netPrice = netPrice - discount;
netPrice = Math.round(netPrice * 100.0) / 100.0
然而,这似乎不起作用,实际上它给了我与上面相同的答案。另一个修复可能涉及使用BigDecimal,但我不知道如何才能在不将netPrice变量更改为不同类型的情况下干净利落地工作(这是我不想做的事情)。有什么想法吗?
发布于 2019-10-13 01:45:28
金融用途Bigdecimal
阅读这篇文章
java-performance.info/bigdecimal-vs-double-in-financial-calculations/
https://stackoverflow.com/questions/58355512
复制相似问题