У меня есть функция discount
, которая принимает параметр 'rate' (double) и обновляет частную переменную netPrice
в моем классе (также 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
. Я понятия не имею, почему это не так, поэтому, если кто-то мог бы пролить свет на то, почему это происходит, было бы здорово.
Что касается исправления, я изначально думал, что смогу обойти эту проблему, используя следующий методдля округления до 2 dp:
public void discount(double rate){
double discount = (netPrice/100) * rate;
netPrice = netPrice - discount;
netPrice = Math.round(netPrice * 100.0) / 100.0
Однако это не похоже на работу, на самом деле это дает мне тот же ответ, что и выше. Другое исправление может включать использование BigDecimal, но я не знаю точно, как я мог бы заставить это работать корректно, не меняя переменную netPrice на другой тип (что я не хочу делать). Есть идеи?