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
Related
import java.util.Scanner;
public class Asgn1 {
//comment practice
/*multi-line comment practice
* no text fill
*/
public static void main(String[] args) {
//user prompted inputs for future calculations
Scanner in = new Scanner(System.in);
System.out.println("The following information is required:");
System.out.println("Enter customer ID: ");
String customerId = in.nextLine();
System.out.println("Enter unit price in decimal format (up to two decimals, e.g. 3.5): ");
String unitPrice = in.nextLine();
System.out.println("Enter quantity (whole numbers only): ");
String orderQuantity = in.nextLine();
System.out.println("Enter product description, (e.g. 'whole wheat bread'): ");
String productDescription = in.nextLine();
System.out.println("Enter discount in decimal format (e.g. .05 = 5%): ");
String appliedDiscount = in.nextLine();
//confirm order data details and display to user
System.out.println("Your order data is as follows: ");
System.out.println("Customer ID: " + customerId);
System.out.println("Unit Price: " + unitPrice);
System.out.println("Order Quantity: " + orderQuantity );
System.out.println("Product Description: " + productDescription);
System.out.println("Applied Discount: " + appliedDiscount);
//calculation formulas based on users input
int beforeDiscount = (Integer.parseInt(unitPrice) * Integer.parseInt(orderQuantity));
int afterDiscount = 1 - (Integer.parseInt(unitPrice) * Integer.parseInt(orderQuantity)) * (appliedDiscount);
//totals before and after discount
System.out.println("Your Order Totals");
System.out.println("Before Discount: ");
System.out.println("After Discount: ");
}
}
I have this java code I want to take the unit price and multiply that by the order quantity, then apply the discount so I can display a before and after discount price.
Originally, when I entered this, I figured out I had to parse the strings for unitPrice and orderQuantity as ints, but when I tried that with the double, I got this message as well on the same line: "Type mismatch: cannot convert from double to int".
I tried looking around at other answers but could not find something that would fix this issue so I'm asking for help, please. What would be the best way to solve this?
In the future, should I try to alter it before it comes in, maybe where they input it, or do I wait until I get the values and then alter that? What would convention dictate?
Thank you for your consideration and assistance.
I change some things on the code... first, the type of variables of unit price and appliedDiscount into double. And also I change the formula to calculate price after discount.
public static void main(String[] args) {
//user prompted inputs for future calculations
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
System.out.println("The following information is required:");
System.out.println("Enter customer ID: ");
String customerId = in.nextLine();
System.out.println("Enter unit price in decimal format (up to two decimals, e.g. 3.5): ");
double unitPrice = in.nextDouble();
System.out.println("Enter quantity (whole numbers only): ");
int orderQuantity = in.nextInt();
System.out.println("Enter product description, (e.g. 'whole wheat bread'): ");
String productDescription = in2.nextLine();
System.out.println("Enter discount in decimal format (e.g. .05 = 5%): ");
double appliedDiscount = in.nextDouble();
//confirm order data details and display to user
System.out.println("Your order data is as follows: ");
System.out.println("Customer ID: " + customerId);
System.out.println("Unit Price: " + unitPrice);
System.out.println("Order Quantity: " + orderQuantity );
System.out.println("Product Description: " + productDescription);
System.out.println("Applied Discount: " + appliedDiscount);
//calculation formulas based on users input
double beforeDiscount = (unitPrice * orderQuantity);
double afterDiscount = beforeDiscount - (beforeDiscount * (appliedDiscount));
//totals before and after discount
System.out.println("Your Order Totals" );
System.out.println("Before Discount: "+ beforeDiscount);
System.out.println("After Discount: " + afterDiscount);
}
I need an instance in my program to work in that if the user inputs a payment number (payment) that is equal to the total price of a checkout with taxation (price3), the program will just list 0.00 as change and not repeat user input as if the user's payment is less than the price. However, when payment equals price3 (payment - price3 == 0), the program goes to the else-if statement. How do I fix this?
Example: price3 == 28, payment == 28, the output after payment input is "You still owe..." and so on instead of "Your change is $0.00".
I think it is skipping the first if-statement in the while loop, but I have no idea why. I already tried moving around the if-statements in the while-loop to no avail.
There are no error messages.
Note: I am still trying to learn Java. Just started recently.
The program code which my question references is displayed below:
import java.util.Scanner;
public class Checkout
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many items are you purchasing?");
int count = input.nextInt();
double price1 = 0;
double price2 = 0;
String userItem = "";
for(int i = 1; i<=count; i++)
{
System.out.println("Please enter the name of the item:");
input.nextLine();
userItem = input.nextLine();
System.out.println("Please enter the price of the item:");
price1 = input.nextDouble();
System.out.println();
System.out.printf("Your item #" + i + " is " + userItem + " with a price of $" + "%.2f", price1);
System.out.println();
price2 = price2 + price1;
}
System.out.println();
System.out.printf("Your total amount is: $" + "%.2f", price2);
double price3 = price2 + (price2 * 0.06);
System.out.println();
System.out.printf("Your total amount with tax is: $" + "%.2f", price3);
System.out.println();
System.out.println("I need a payment!");
double payment = input.nextDouble();
boolean condition = false;
while(condition == false)
{
if(payment - price3 == 0)
{
condition = true;
}
else if(payment < price3)
{
System.out.println();
System.out.printf("You still owe " + "%.2f", (price3-payment));
System.out.println();
System.out.println("I need a better payment!");
payment = input.nextDouble();
}
else
{
condition = true;
}
}
double change = payment - price3;
System.out.println();
System.out.printf("Your change is: $" + "%.2f", change);
}
}
The core of your problem lies in (1) expecting exact equality of floating-point value, and (2) displaying quantities to 2 decimal places.
Given the user is told the amount to pay (price3) using 2 places of decimals, even if he enters that exact same value as payment, it may not match the true value of price3.
Ideally you should do all calculation in pennies (or whatever the smaller unit of this currency is). Failing that, your criterion for having paid the right amount should be something like the difference between price and payment is less than 0.01.
In the stated case
Example: price3 == 28, payment == 28, the output after payment input
is "You still owe..." and so on instead of "Your change is $0.00".
if the price before tax is 26.415 it makes the price after tax 27.9999, which displays as 28.00 but is not equal to 28.00. Neither 26.41 nor 26.42 get you to an after-tax displayed price of 28.00.
that is happening because of price3=price2+(price2*0.06). So, when it is comparing payment with price3, it is always less. See below
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'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%
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.