I'm trying to use java's NumberFormat class and the getPercentInstance method in a program to calculate tax. What I want the program to display is a percentage with two decimal places. Now, when I tried to format a decimal as a percent before, Java displayed something like 0.0625 as 6%. How do I make Java display a decimal like that or say 0.0625 as "6.25%"?
Code Fragment:
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();
System.out.print("Enter the quantity of items to be purchased: ");
quantity = scan.nextInt();
System.out.print("Enter the unit price: ");
unitPrice = scan.nextDouble();
subtotal = quantity * unitPrice;
final double TAX_RATE = .0625;
tax = subtotal * TAX_RATE;
totalCost = subtotal + tax;
System.out.println("Subtotal: " + fmt1.format(subtotal));
System.out.println("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE));
System.out.println("Total: " + fmt1.format(totalCost));
You can set the minimum number of fraction digits on a NumberFormat instance using setMinimumFractionDigits(int).
For instance:
NumberFormat f = NumberFormat.getPercentInstance();
f.setMinimumFractionDigits(3);
System.out.println(f.format(0.045317d));
Produces:
4.532%
Related
The program is to calculate the total price for meat but I keep getting the output of $.68 instead of $10.89, any help would be greatly appreciated. While i'm sure it's most likely a error with the last println statement any help would be useful.
/**********************************************************************
Program: Deli.java
Description: Computes the price of a deli item given the weight (in ounces)
and the price per pound.
***********************************************************************/
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Deli
{
/* -------------------------------------------------------------------------------------
The function main reads in the price per pound of a deli item
and the number of ounces of a deli item then computes the total price
and prints a "label" for the item that includes the unit price (per pound),
the weight and total price.
----------------------------------------------------------------------------------------*/
public static void main (String[] args)
{
final double OUNCES_PER_POUND = 16.0;
double pricePerPound; // price per pound
double weightOunces; // weight in ounces
double weight; // weight in pounds
double totalPrice; // total price for the item
Scanner scan = new Scanner(System.in);
/* ------------------------------------------------------------------------
Declare money as a NumberFormat object and use the
getCurrencyInstance method to assign it a value.
Declare fmt as a DecimalFormat object and instantiate
it to format numbers with at least one digit to the left of the
decimal and the fractional part rounded to two digits.
Prompt the user and read in each input.
-------------------------------------------------------------------------*/
NumberFormat format1 = NumberFormat.getCurrencyInstance();
DecimalFormat format2 = new DecimalFormat("0.##");
System. out. println ("Welcome to the CS Deli! ! \n ");
System.out.print ("Enter the price per pound of your item: ");
pricePerPound = scan.nextDouble();
System.out.print ("Enter the weight (ounces): ");
weightOunces = scan.nextDouble();
// Convert ounces to pounds and compute the total price
weight = weightOunces / OUNCES_PER_POUND;
totalPrice = pricePerPound * weight;
// Print the unit price, weight, and total price using the formatting objects.
// Format the weight in pounds and use the money format for the prices.
System.out.println("\nUnit Price: " + format1.format(pricePerPound) + " per pound");
System.out.println("\nWeight: " + format2.format(weightOunces) + " pounds");
System.out.println("\nTotal Price: " + format1.format(totalPrice));
}
}
"The inputs are $4.25 for the unit price, and 2.56 pounds."
I think you're a little confused here as to how your application is expecting its input. The prompts ask for The price per pound:
Enter the price per pound of your item: 4.25
and then asks to enter The weight in ounces:
Enter the weight (ounces): 2.56
Again, it asks to enter in ounces not pounds. The code then takes this ounces input (2.56) and converts it to pounds which ends up being about 0.16 pounds. Well, I suppose 0.16 pounds of the item which is priced at $4.25 per pound will cost you $0.68 dollars (or just 68 cents).
If you really wanted to purchase 2.56 pounds of the item then you should have supplied 40.96 (2.56 * 16) in the ounces prompt.
As #JohnBayko has already so graciously pointed out, you are displaying the wrong value in your output from this code line:
System.out.println("\nWeight: " + format2.format(weightOunces) + " pounds");
It should be your conversion value displayed not what was entered:
System.out.println("\nWeight: " + format2.format(weight) + " pounds");
Ok, how do I round a decimal to the 2nd decimal place instead of just the first decimal place? I had to create a menu, where the "customer" orders food and we had to have the subtotal and tax and tip included. My code works fine unless the grand total is something like $3.8 when it should be $3.80. How can I fix that by only using Math.round()? My code for the money part of the menu is
double SUBtotal = subTotal * 100.00;
System.out.println("Your current total is: $" +
Math.round(SUBtotal)/100.00);
System.out.println("Options:");
System.out.println(" 1. Order another item");
System.out.println(" 2. Checkout");
mainOp = scan.nextInt();
if (mainOp==2)
{
System.out.println(Order);
double tax = subTotal * 0.0825;
double taxSubtotal = tax + subTotal;
double please = taxSubtotal * 100.00;
double taxSubtotal2 = Math.round(please) / 100.00;
System.out.println("\nSubtotal (with tax): $ " + taxSubtotal2);
System.out.println("Tip: $");
double tip = scan.nextDouble();
double total = taxSubtotal + tip;
double total2 = total * 100.00;
double total3 = Math.round(total2) /100.00;
System.out.println("Final Total: $" + total3);
System.out.println();
System.out.println("Thank You For Ordering!");
}
Thank you very much!
Here is a small code snippet using DecimalFormat to solve your problem.
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(total3));
This will print your decimal value as a string having two decimal places appended.
Additionally, you can declare one decimalFormat variable and use it through out your code everywhere, wherever you want to display a 2 decimal place value.
Thanks
If you want to 3.80 instead of 3.8, use below code after getting total. String is that is you want.
DecimalFormat f = new DecimalFormat("##.00");
String d = f.format(taxSubtotal2);
Started taking a Java class at school and doing extra credit
and need help figuring out how to just have 2 decimal places.
Thank you for the help.
Christopher
import java.util.Scanner;
public class ChapterTwoEx8 {
public static void main(String[] args) {
//Create a Scanner object to read keyboard input.
Scanner keyboard = new Scanner(System.in);
//Declare Constants
final double SALES_TAX_RATE = 0.07;
final double TIP = 0.15;
//Declare Variables
double yourMealsPrice;
double wifeMealsPrice;
double sum;
double tip;
double totalCostOfMeal;
double salesTax;
//Get the prices of the meals.
System.out.println("Please enter the price of your wives meal.");
wifeMealsPrice = keyboard.nextDouble();
System.out.println("Please enter the price of your meal.");
yourMealsPrice = keyboard.nextDouble();
//Calculate cost of the meals.
sum = (double) wifeMealsPrice + yourMealsPrice;
//Calcute the sales tax
salesTax = (double) sum * SALES_TAX_RATE;
//Calcute tip
tip = (double) sum * TIP;
//Calcute total cost of meal
totalCostOfMeal = (double) sum + tip + salesTax;
System.out.println("Your meals were $ " + sum);
System.out.println("The total tax you paid is $ " + salesTax);
System.out.println("The tip you should leave is $ " + tip);
System.out.println("The amount of money you paid to keep your wife happy this night is $ " + totalCostOfMeal);
}
}
Use NumberFormat
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
String formattedSum = nf.format(sum);
System.out.println("Your meals were $ " + formattedSum);
System.out.println("The total tax you paid is $ " + nf.format(salesTax));
System.out.println("The tip you should leave is $ " + nf.format(tip));
System.out.println("The amount of money you paid to keep your wife happy this night is $ " + nf.format(totalCostOfMeal));
Or, you could get rid of the dollar signs and just use NumberFormat.getCurrencyInstance();
instead of using NumberFormat.getInstance();
I want to figure out how I can format the output as money. As I am a beginner at Java, I would like the most simple solution possible although I am open to all suggestions.
public static void main(String[] args)
{
int numUnits;
double price;
String item;
Scanner scan = new Scanner(System.in);
// get the data
System.out.println("How many units?");
numUnits = scan.nextInt();
System.out.println("What is the price?");
price = scan.nextDouble();
scan.nextLine();
System.out.println("What is the name of the item?");
item = scan.nextLine();
//calculations
double totalCost = numUnits * price;
System.out.println(numUnits + " units of "+ item + " were purchased for $"+
price + " each for a total cost of $" + totalCost);
}
}
Well there are a number of ways you might be able to do it, you could use NumberFormat.getCurrencyInstance(), which will allow you to format the value based on the current locale properties...
System.out.println(numUnits + " units of "+ item + " were purchased for $"+
price + " each for a total cost of $" + NumberFormat.getCurrencyInstance().format(totalCost));
You could also format the NumberFormat to suit you needs by getting a reference to the instance first...
NumberFormat nf = NumberFormat.getCurrencyInstance();
// Customise format properties...
double amount =500.0;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(new Locale("en", "US"));
System.out.println(currencyFormatter.format(amount));
You should use proper locale for which ever currency you awnt to use
I am getting an error trying to code a program which calculates interest on a loan, and displays information back with certain decimal positions. I need the loanInterest to display at 3.546%, or something like that with 3 decimal places. I was able to get the totalInterest to display properly, but I dont know if this is because it was a new value I just established. When I try to run my program as seen below, I get a "float cannot be dereferenced" error.
public class SarahShelmidineModule2Project {
public static void main(String[] args) {
//Being programing for Module 2 project
// Welcome the user to the program
System.out.println("Welcome to the Interest Calculator");
System.out.println(); // print a blank line
// create a Scanner object named sc
Scanner sc = new Scanner(System.in);
// perform interest calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get info from user on loan amount and interest rates and store data
System.out.print("Enter loan amount: ");
double loanAmount = sc.nextDouble();
System.out.print("Enter interest rate: ");
float loanInterest = sc.nextFloat();
// calculate the interest and convert to BigDecimal and rounding for totalInterest
BigDecimal decimalloanAmount = new BigDecimal (Double.toString(loanAmount));
BigDecimal decimalloanInterest = new BigDecimal (Double.toString(loanInterest));
BigDecimal totalInterest = decimalloanAmount.multiply(decimalloanInterest);
totalInterest = totalInterest.setScale(2, RoundingMode.HALF_UP);
loanInterest = loanInterest.setScale(3, RoundingMode.HALF_UP);
System.out.println(); // print a blank line
// display the loan amount, loan interest rate, and interest
// also format results to percent and currency
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
String message = "Loan amount: " + currency.format(loanAmount) + "\n"
+ "Interest rate: " + percent.format(loanInterest) + "\n"
+ "Intrest: " + currency.format(totalInterest) + "\n";
System.out.println(message);
// inquire if user would like to continue with application
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
Below is the error I get when I run this:
Welcome to the Interest Calculator
Enter loan amount: 10932
Enter interest rate: .0934
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - Erroneous sym type: <any> at
sarahshelmidinemodule2project.SarahShelmidineModule2Project.main(SarahShelmidineModule2Project.java:45)
Just change
float loanInterest = sc.nextFloat();
with
BigDecimal loanInterest = new BigDecimal(sc.nextFloat());
and you will resolve "float cannot be derefenced" since float is a primitive type and has not method setScale.
About printing right number of decimals, use something like this:
String currencySymbol = Currency.getInstance(Locale.getDefault()).getSymbol();
System.out.printf("%s%8.5f\n", currencySymbol, totalInterest);
This code will use 5 decimals, but be sure that your BigDecimal scale is at least 5, otherwise you will get not significant zeros.