This site requires JavaScript, please enable it in your browser!
Greenfoot back
dbutts1@stumail.com
dbutts1@stumail.com wrote ...

2017/12/14

Decimal.Format

dbutts1@stumail.com dbutts1@stumail.com

2017/12/14

#
I am trying to use the Decimal.Format to multiply a double price; by a discount using a 2 digit int, not a double, to get the double salePrice. I think the only error I have is in the multiplication to produce the sales price. Here is my code. double price; int discount; double salePrice; DecimalFormat money = new DecimalFormat("$0.00"); price = Double.parseDouble(Greenfoot.ask("What is the price of the product")); discount = Integer.parseInt(Greenfoot.ask("What is the amount of the discount? Use a two digit number such as 30")); // process the Double price multiplied by the two intiger discount, to output th sale price salePrice = (double price)*(discount); showText("Price: " + money.format(price), getWidth()/2, getHeight()/2); showText("Discount: " + money.format(discount) , getWidth()/2, getHeight()/2 - 20); showText("Sale Price: " + money.format(salePrice), getWidth()/2, getHeight()/2 - 40); Greenfoot.stop();
danpost danpost

2017/12/15

#
The 'price' is already a variable of type double; it is the 'discount' that need to be converted to a double type value:
1
salePrice = price*((double)discount);
There are still two problems with this formula: (1) multiplying 'price' by any value greater than one will increase the value (not much of a discount -- huh); and (2) the discounted amount needs subtracted from the price. What you probably then want is something like this:
1
salePrice = price*(1.0-(double)discount/100.0);
dbutts1@stumail.com dbutts1@stumail.com

2017/12/15

#
Thank you. I've been looking at this so long I see that my main issue was I never put in import java.text.DecimalFormat;
You need to login to post a reply.