|
-
June 22nd, 2011, 10:26 PM
#1
Formating Double as a Decimal
You guys have been a lot of help so far. I've had to create a program that has an array of 5 items, where one side is an item, the other is a price of that item. I've created everything, but I'm struggling to format the price as a decimal. I have 2 classes written. I am posting the class that has my variables assigned. I think that's where I need to do it. I successfully did this last week with an array where the user entered 5 values, but as each array has 2 values, the method I learned last week formatter.format(x); isn't working. printf wouldn't work either. Anyways, here is my code. I need Price to have a set 2 decimal places on output.
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Item
{
//private instance variables
private String Name;
private double price;
//Create object to format as decimal
NumberFormat formatter = new DecimalFormat("#0.00");
public String getName()
{
return this.Name;
}
public void setItemName(String Name)
{
this.Name = Name;
}
public double getPrice()
{
return this.price;
}
public void setPrice(double Name)
{
this.price = price;
}
public String toString()
{
return this.getName() + " $" + this.getPrice();
}
//constructor
public Item(String Name, double price)
{
this.Name = Name;
this.price = price;
}
}
My array looks like: ItemArray[0] = new Item("Donut", 1.50);
I'm thinknig maybe instead of a double for price I should use a string, but that is only a work around and not a real solution. It'd work for this program, but it doesn't teach me anything.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|