我有一个函数discount
,它接受一个'rate'参数(一个double值),并将我班级(也是一个double值)中的私有变量netPrice
更新为减价后的价格。计算似乎有效,但是存在问题;它会产生误差。
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
。我不知道为什么会这样,所以如果有人可以阐明为什么会这样,那就太好了。
至于修复,我最初认为我可以使用以下方法将其四舍五入到2 d.p。:
public void discount(double rate){
double discount = (netPrice/100) * rate;
netPrice = netPrice - discount;
netPrice = Math.round(netPrice * 100.0) / 100.0
但是,这似乎不起作用,实际上,它给了我与上述相同的答案。另一个修复程序可能涉及使用BigDecimal,但我不知道如何在不将netPrice变量更改为其他类型的情况下使它正常工作(我不希望这样做)。有什么想法吗?
答案 0 :(得分:0)
用于财务用途Bigdecimal
阅读本文
java-performance.info/bigdecimal-vs-double-in-financial-calculations /