java - Method not correctly calculating and displaying values? -
i'd appreciate this.
for example, code is;
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; } }
and output is:
peanut butter fudge $8.0 2.25 lbs @ $3.99
why displaying $8.0 instead of $8.97?
any appreciated! thanks.
try int costincents = (int) (cost*100)
concrete example: on cost = 3.5 ==> (int)cost*100 = 300
on cost = 3.5 ==> (int) (cost*100) = 350
Comments
Post a Comment