我很感谢这个帮助。方法不正确计算和显示值?
例如,我的代码是;
class Candy extends DessertItem
{
double weight;
double price;
Candy(String n, double w, double p)
{
super(n);
weight = w;
price = p;
}
public double getCost()
{
double cost = weight*price;
int costinCents = (int)cost*100;
cost = costinCents /100.0;
return cost;
}
public String toString()
{
return name+"\t\t\t\t$" + getCost() + "\n\t" + weight + " lbs @ $" + price;
}
}
,输出是:
Peanut Butter Fudge $8.0
2.25 lbs @ $3.99
为什么显示$ 8.0,而不是$ 8.97?
任何帮助,将不胜感激!谢谢。
你认为'(int)cost * 100是什么意思? – Savior
哎呀,我的错。我如何让它只显示2个小数点? – emansour619
http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java – Savior