0

So I am at somewhat of a loss here. I am trying to format my strings to be only 2 decimal places. I know what you are thinking and I have to have them as strings in order to append them to my JTextArea (these are a small part of my arrayList). So I have converted the doubles into strings using String.valueof() which works fine, however I need to format them in order to print out the string with 2 decimal places. My delcarations and such are as follows

class inventoryItem { //Delcare variables below

String itemName;
String newUnit;
String newFee;
String newValue;
String newInventoryValue;
int itemNumber;
int inStock;
double unitPrice;
double value;
double restockingFee;

double inventoryValue;

public inventoryItem(String itemName, int itemNumber, int inStock, double unitPrice) { //declare variables for this class
    this.itemName = itemName;
    this.itemNumber = itemNumber;
    this.inStock = inStock;
    this.unitPrice = unitPrice;
    restockingFee = .05 * value;
    stockValue();

}

public void stockValue() {
    value = unitPrice * inStock;
    restockingFee = .05 * unitPrice;
    inventoryValue = restockingFee + value;
    newUnit = String.valueOf((double) unitPrice);
    newFee = String.valueOf((double) restockingFee);
    newValue = String.valueOf((double) value);
    newInventoryValue = String.valueOf(inventoryValue);

I have tried to do something like

outputText.append("something = $" + (String.format("%.2f, newUnit))

but that doesn't seem to work. Is there a way that I can do it while using String.valueOf?

1 Answer 1

2

Use DecimalFormat

Sample:

double unitPrice = 1.23235;
java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat( "#,###,###,##0.##" );
String formattedUnitPrice = decimalFormat.format(unitPrice);

Output is going to be 1.23

Sign up to request clarification or add additional context in comments.

3 Comments

So are you saying to do this at the point of printing it out, or prior to using the String.valueof()? The reason I ask is because it has to be converted to string prior to printing it out.
Yes, I'm saying, you should better format your value with a pre defined Decimalformat. Try to google DecimalFormat. That's what you need.
I marked your answer as correct, however I had to modify this slightly to get it to work. I ended up importing DecimalFormat and then creating a new format somewhat like you said above. However in order to get it to print out correctly I had to do something like 'formatted.format(unitPrice)' and it worked like a charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.