Im having trouble to find a way for formatting this:
System.out.println("Product price reported as $" + price + " before tax and $" + result + " after " + this.tax + " % tax"):
Im trying like this.
String formatDecimals = String.format("%.2f","Product price reported as $" + price + " before tax and $" + result + " after " + this.tax + " % tax"):
I want to have two decimals. Any help
You are trying to format a string as a float, this will not work. The whole text has to go into the "format" parameter:
String formatDecimals = String.format("Product price reported as $%.2f before tax and $%.2f after %.2f %% tax", price, result, this.tax);
Related
I would like this program below to capture user input (first product name, then costs), and then output to the console, and ask the user if they would like anything else, and if they do, it will do it again and output the next product and costs.
If the user replies with no, then I want it to output a list of the items by number and name, and then the total costs of how every many items were requested, and then a total overall cost.
Here is my code so far; I want to understand how to get the total overall costs and list each item. I feel like I am very close.
public static void main(String[] args) {
/////////Initialize everything here/////////
Scanner keyboard = new Scanner (System.in);
String nameProd;
String response;
int items = 0;
int costMat;
int hoursReq;
int payPerHr = 15; //cost per hour for only one employee, who is also the owner (me)
double shipping = 13.25; //shipping cost remains constant even with multiple items
//////////////////////////////////////////////////////////////////////////////////
System.out.println("================================="
+ "\nWelcome to Ryan's Computer Store!"
+ "\n=================================");
do{
items++;
//////////////////////////////////////////
System.out.print("Enter product name: ");
nameProd = keyboard.next();
////////////////////////////////////////////////
System.out.print("Enter cost of materials: $");
costMat = keyboard.nextInt();
System.out.print("In hours, how soon would you prefer that this order is completed?: ");
hoursReq = keyboard.nextInt();
//////////////////////////////////////////////////////////////////////////////////////////
System.out.println("===================================================================="
+ "\n============================"
+ "\n>>>>>>Rundown of costs<<<<<<"
+ "\nItem #: " + items
+ "\nItem Name: " + nameProd
+ "\nCost of Materials: $" + costMat
+ "\n===>Hours spent creating the product: " + hoursReq + " hours"
+ "\n===>Employee Pay Per Hour: $" + payPerHr);
int priceMarkup = hoursReq*payPerHr;
//////////////////////////////////////////////////////
System.out.println("Price of product after markup: $"
+ (priceMarkup+costMat));
//////////////////////////////////////////////////////
System.out.println("===>Shipping Fee: $" + shipping);
//////////////////////////////////////////////
int costBeforeShipping = priceMarkup+costMat;
double totAmt = shipping+costBeforeShipping;
//////////////////////////////////////////////////////
System.out.println("Amount to be charged for item #" + items + " (" + nameProd + ")" + ": $" + totAmt
+ "\n============================");
//////////////////////////////////////////////////////////////////////////////
System.out.print("========================================================"
+ "\nIs there anything else that you would like to order?: ");
response = keyboard.next();
}
while
(response.equalsIgnoreCase("yes"));
System.out.println(">>>>>========================================================<<<<<\nTOTAL AMOUNT TO BE CHARGED FOR " + items + " ITEMS: " + "\nShipping (flat fee): " + shipping + "\nSum of Items: ");
}}
You need a list to hold item names and one temporary variable to hold sum of prices. I think below code will help you.
Scanner keyboard = new Scanner (System.in);
String nameProd;
String response;
int items = 0;
int costMat;
int hoursReq;
int payPerHr = 15; //cost per hour for only one employee, who is also the owner (me)
double shipping = 13.25; //shipping cost remains constant even with multiple items
//////////////////////////////////////////////////////////////////////////////////
List<String> orderItems = new ArrayList<>();
double totalPrice=0;
System.out.println("================================="
+ "\nWelcome to Ryan's Computer Store!"
+ "\n=================================");
do{
items++;
//////////////////////////////////////////
System.out.print("Enter product name: ");
nameProd = keyboard.next();
////////////////////////////////////////////////
System.out.print("Enter cost of materials: $");
costMat = keyboard.nextInt();
System.out.print("In hours, how soon would you prefer that this order is completed?: ");
hoursReq = keyboard.nextInt();
//////////////////////////////////////////////////////////////////////////////////////////
System.out.println("===================================================================="
+ "\n============================"
+ "\n>>>>>>Rundown of costs<<<<<<"
+ "\nItem #: " + items
+ "\nItem Name: " + nameProd
+ "\nCost of Materials: $" + costMat
+ "\n===>Hours spent creating the product: " + hoursReq + " hours"
+ "\n===>Employee Pay Per Hour: $" + payPerHr);
orderItems.add(nameProd);
int priceMarkup = hoursReq*payPerHr;
//////////////////////////////////////////////////////
System.out.println("Price of product after markup: $"
+ (priceMarkup+costMat));
//////////////////////////////////////////////////////
System.out.println("===>Shipping Fee: $" + shipping);
//////////////////////////////////////////////
int costBeforeShipping = priceMarkup+costMat;
double totAmt = shipping+costBeforeShipping;
totalPrice+=totAmt;
//////////////////////////////////////////////////////
System.out.println("Amount to be charged for item #" + items + " (" + nameProd + ")" + ": $" + totAmt
+ "\n============================");
//////////////////////////////////////////////////////////////////////////////
System.out.print("========================================================"
+ "\nIs there anything else that you would like to order?: ");
response = keyboard.next();
}
while
(response.equalsIgnoreCase("yes"));
System.out.println(">>>>>========================================================<<<<<\nTOTAL AMOUNT TO BE CHARGED FOR ITEMS: " + orderItems + "\nShipping (flat fee): " + shipping + "\nSum of Items: "+totalPrice);
}
I'm trying to find out why the %.2f declaration when outputting a decimal isn't working in my code, I've checked other similar questions but I can't seem to locate the issue in the specific logic error I'm receiving. When I go to compile my program it compiles fine, I go to run it and everything outputs fine until I get to the final cost where I'm trying to only display that decimal value with 2 decimal places.
I get an exception in thread "main"
Java.util.illegalformatconversionexception f! = Java.lang.string
At java.util.Formatter$formatspecifier.failconversion(Unknown Source)
At java.util.Formatter$formatspecifier.printFloat(Unknown Source)
At java.util.Formatter.format(Unknown Source)
At java.io.printstream.format(Unknown Source)
At java.io.printstream.printf(Unknown Source)
At Cars.main(Cars.java:27)
Here is my code:
import java.util.Scanner;
public class Cars
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int carYear, currentYear, carAge;
double costOfCar, salesTaxRate;
double totalCost;
String carModel;
System.out.println("Please enter your favorite car model.");
carModel = input.nextLine();
System.out.println("Please enter the year of the car");
carYear = input.nextInt();
System.out.println("Please enter the current year.");
currentYear = input.nextInt();
carAge = currentYear - carYear;
System.out.println("How much does the car cost?");
costOfCar = input.nextDouble();
System.out.println("What is the sales tax rate?");
salesTaxRate = input.nextDouble();
totalCost = (costOfCar + (costOfCar * salesTaxRate));
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f",totalCost + " " + " dollars.");
}
}
I'm not exactly sure what's causing the issue.
Try:
System.out.printf("The model of your favorite car is %s, the car is %d years old, the total of the car is %.2f dollars.", carModel, carAge, totalCost);
Or the more readable:
System.out.printf("The model of your favorite car is %s," +
" the car is %d years old," +
" the total of the car is %.2f dollars.",
carModel, carAge, totalCost);
It's because %.2f is replaced with the entire second argument in that method call. The problem is that by specifying f in %.2f, you are saying that the second argument is a float or double. The second argument in this case is totalCost + " " + " dollars." which evaluates to a string.
To fix this problem, you need to make the second argument be a float or double. This can be achieved by moving + " " + " dollars." from the end of the second argument to the end of the first argument, like so:
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f" + " " + " dollars.",totalCost);
You can also remove many of the unnecessary concatenations from that line, resulting in this:
System.out.printf("The model of your favorite car is" + carModel + ", the car is " + carAge + " years old, the total of the car is %.2f dollars.", totalCost);
The variable has to go as a parameter to the System.out.printf() function. The "%.2f" will be replaced by the double value that is passed as the second parameter.
For Example:
System.out.printf("The value is %.2f", value);
The same thing is true for other variable types and for multiple variables,
String str = "The value is: ";
double value = .568;
System.out.printf("%s %.2f", str, value);
This will output: "The value is: .57"
The project I am working on requires a bank account balance to be printed using a toString method. I am not allowed to add any methods to my current program, but I need to format my myBalance variable to a double that goes to two decimal places instead of one. In this particular instance my program should be printing 8.03, but it is printing 8.0.
Here is my toString method:
public String toString()
{
return"SavingsAccount[owner: " + myName +
", balance: " + myBalance +
", interest rate: " + myInterestRate +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
I am very new to Java still, so I would like to know if there is a way to implement %.2f into the string somewhere to format only the myBalance variable. Thank you!
Use String.format(...) for this:
#Override
public String toString() {
return "SavingsAccount[owner: " + myName +
", balance: " + String.format("%.2f", myBalance) +
", interest rate: " + String.format("%.2f", myInterestRate) +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
or more succinctly:
#Override
public String toString() {
String result = String.format("[owner: %s, balance: %.2f, interest rate: %.2f%n" +
"number of withdrawals this month: %d, service charges for this month: %.2f, " +
"myStatusIsActive: %s]",
myName, myBalance, myInterestRate, myMonthlyWithdrawCount,
myMonthlyServiceCharges, myStatusIsActive);
return result;
}
Note that khelwood asked about my use of "%n" for a new-line token rather than the usual "\n" String. I use %n because this will allow the java.util.Formatter to get a platform specific new-line, useful in particular if I want to write the String to a file. Note that String.format(...) as well as System.out.printf(...) and similar methods use java.util.Formatter in the background so this applies to them as well.
Use String.format()
Example :
Double value = 8.030989;
System.out.println(String.format("%.2f", value));
Output :
8.03
This question already has answers here:
How do I round a double to two decimal places in Java? [duplicate]
(21 answers)
Closed 8 years ago.
final double YearDep= 0.15; //this is for each year a car loses of the value before
double HybridDepreciation= HybridCarCost * Math.pow(1-YearDep,5);
double HybridFuelCost=(Miles*5*GasCost)/HybridCarMPG;
double GasPowerDepreciation=GasPowerCost * Math.pow(1-YearDep,5);
double GasPowerFuelCost=(Miles *5*GasCost)/GasPowerMPG;
double HybridTotalCost=HybridCarCost - HybridDepreciation + HybridFuelCost;
double GasPowerTotalCost= GasPowerCost - GasPowerDepreciation + GasPowerFuelCost;
System.out.printf("The total cost for the " + HybridName + " " + "is" +" $"+ HybridTotalCost);
System.out.println();
System.out.printf("The total cost for the " + GasPowerName + " "+ "is" + " $"+ GasPowerTotalCost);
use DecimalFormat for this:
DecimalFormat df = new DecimalFormat(".00");
System.out.printf("The total cost for the " + HybridName + " " + "is" +" $"+ df.format(HybridTotalCost));
System.out.println();
System.out.printf("The total cost for the " + GasPowerName + " "+ "is" + " $"+ df.format(GasPowerTotalCost));
Or you can use
String.format("The total cost for the %s is $%.2f", HybridName ,HybridTotalCost)
DecimalFormat df = new DecimalFormat("#.00");
then
df.format(<your_value>);
Or
System.out.println( String.format( "%.2f", <your_value> ) );
You can use.
double roundOff1 = (double) Math.round(HybridTotalCost);
double roundOff2 = (double) Math.round(GasPowerTotalCost);
and you can also use.
DecimalFormat df = new DecimalFormat("###.##");
System.out.printf("The total cost for the " + HybridName + " " + "is" +" $"+ df.format(HybridTotalCost));
System.out.println();
System.out.printf("The total cost for the " + GasPowerName + " "+ "is" + " $"+df.format(GasPowerTotalCost));
double roundOff = Math.round(a*100)/100.0;
or
DecimalFormat number = new DecimalFormat("#.00");
number.format(new Double(2223.8990))
I am very new to Java and playing with displaying a message with GUI. So if use the console
System.out.printf("Your total montly bill is $%.2f", totalCost);
gives me the output with decimal the way it should. I am trying to do the same thing with this, but I get more digits after the decimal because totalCost is a type double. How can I format the output to only show two digits after the decimal? Thanks.
JOptionPane.showMessageDialog(null, "Your monthly payment is " + totalCost);
You could do:
JOptionPane.showMessageDialog(null, String.format("Your monthly payment is $%.2f", totalCost));
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
JOptionPane.showMessageDialog(null, "Your monthly payment is " + df.format(d));
System.out.println(df.format(d));
Class DecimalFormat API
You can also do:
JOptionPane.showMessageDialog(this, "Your monthly payment is " + totalCost);
DecimalFormat df = new DecimalFormat("#.##");
String hour = JOptionPane.showInputDialog("Please input your hourly salary: ");
double hr = Double.parseDouble(hour);
double dr = hr * 8;
double wr = hr * 40;
double mr = hr * 160;
double yr = mr * 12;
JOptionPane.showMessageDialog(null, "Yearly: " + df.format(yr) + " / " + "Monthly: "
+ df.format(mr) + " / " + "Weekly: "+ df.format(wr) + " / " + "Hour: " + df.format(hr),
"Yearly Salary Calculator by the hour", JOptionPane.OK_OPTION, icon);