0

I'd appreciate some help with this.

For example, my 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 the output is:

Peanut Butter Fudge             $8.0
    2.25 lbs @ $3.99

Why is it displaying $8.0 instead of $8.97?

Any help would be appreciated! Thanks.

1 Answers1

0

Try int costinCents = (int) (cost*100)

Concrete example: on cost = 3.5 ==> (int)cost*100 = 300

on cost = 3.5 ==> (int) (cost*100) = 350

Tomer Something
  • 770
  • 1
  • 10
  • 24
  • Got it. How would I get it to display $8.97 instead of $8.977500000000001? I tried using the above link with the .2% and it didn't work because I am using a return, and not a system.out. – emansour619 Apr 22 '16 at 00:42
  • Please refer to this: http://stackoverflow.com/questions/2538787/how-to-display-an-output-of-float-data-with-2-decimal-places-in-java – Tomer Something Apr 22 '16 at 00:43
  • I saw that, but how would I interpret it into my return statement? return name+"\t\t\t\t$" + getCost() + "\n\t" + weight + " lbs @ $" + price; – emansour619 Apr 22 '16 at 00:46
  • DecimalFormat myFormatter = new DecimalFormat("0.##"); String output = myFormatter.format(floatValue); EXAMPLE: when floatValue = 35.12345f, output is 35.12 – Tomer Something Apr 22 '16 at 01:07