...

View Full Version : Help formatting to dollars



anonymous9
01-27-2012, 11:09 PM
I can't figure out how to convert the total amount in my output to dollars format using NumberFormat. I don't want it to say $257.40000000000003 when I enter 13 packages Can someone help me.

OUTPUT:
Software Packages for sale $99 or less based on quantity.
Enter the Number of Packages Purchase:13
Total without discount is
$1287.0
Total discount is
$257.40000000000003
Total with discount is
$1029.6



import java.util.Scanner;

public class CompoundAssignment {

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);
int quantity;
double total, total1, discount;

System.out.print("Software Packages for sale $99 or less based on quantity.\n");
System.out.print("Enter the Number of Packages Purchase:");
quantity = keyboard.nextInt();

if (quantity < 20) {

total = (quantity * 99) * .20;
total1 = quantity * 99;
discount = total1 - total;

System.out.println("Total without discount is \n$" + total1);
System.out.println("Total discount is \n$" + total);
System.out.println("Total with discount is \n$" + discount);

}// end if
else if (quantity > 19 && quantity < 50) {
total = (quantity * 99) * .33;
total1 = quantity * 99;
discount = total1 - total;
System.out.println("Your Total without discount is \n$" + total1);
System.out.println("The discount is \n$" + total);
System.out.println("The discounted total \n$" + discount);

}// end if
else if (quantity > 49 && quantity < 100) {
total = (quantity * 99) * .42;
total1 = quantity * 99;
discount = total1 - total;
System.out.println("Total without discount is \n$" + total1);
System.out.println("Total discount is \n$" + total);
System.out.println("Total with discount is \n$" + discount);

}// end if
else if (quantity > 99) {
total = (quantity * 99) * .49;
total1 = quantity * 99;
discount = total1 - total;
System.out.println("Total without discount is \n$" + total1);
System.out.println("Total discount is \n$" + total);
System.out.println("Total with discount is \n$" + discount);

}// end if

}// end main
} // end class

Fou-Lu
01-28-2012, 04:04 AM
Using the NumberFormat is extremely easy when you get used to it:


NumberFormat nfc = NumberFormat.getCurrencyInstance(Locale.US);

Simple as this. nfc is now capable of formatting any input as a currency number in the provided locale. It doesn't carry a value with it by itself, so you may continue to use the same instance.
To use:


System.out.println("Total without discount is \n" + nfc.format(total1));
System.out.println("Total discount is \n" + nfc.format(total));
System.out.println("Total with discount is \n" + nfc.format(discount));



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum