I am new to Java and I'm trying to figure out how to dynamically calculate the change to the nearest 10 dollars. For instance, the user inputs a value (34.36), my code then calculates tip, tax, and total amount for the bill (total 44.24). Without user input, I need to calculate the change from $50.00. I've tried to round up to 50.00 from 44.24 with no luck, obviously I am doing something wrong. I've tried Math.round and tried to find the remainder using %. Any help on how to get the total change due to the nearest 10 dollar value would be great. Thank you in advance, below is my code:
Full dis-closer, this is a homework project.
import java.util.Scanner;
import java.text.NumberFormat;
import java.lang.Math.*;
public class test1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//Get input from user
System.out.println("Enter Bill Value: ");
double x = sc.nextDouble();
//Calculate the total bill
double salesTax = .0875;
double tipPercent = .2;
double taxTotal = (x * salesTax);
double tipTotal = (x * tipPercent);
double totalWithTax = (x + taxTotal);
double totalWithTaxAndTip = (x + taxTotal + tipTotal);
//TODO: Test Case 34.36...returns amount due to lower 10 number
//This is where I am getting stuck
double totalChange = (totalWithTaxAndTip % 10);
//Format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
//Build Message / screen output
String message =
"Bill Value: " + currency.format(x) + "\n" +
"Tax Total: " + currency.format(taxTotal) + "\n" +
"Total with Tax: " + currency.format(totalWithTax) + "\n" +
"20 Percent Tip: " + currency.format(tipTotal) + "\n" +
"Total with Tax and 20 Percent Tip: " + currency.format(totalWithTaxAndTip) + "\n" +
"Total Change: " + currency.format(totalChange) + "\n";
System.out.println(message);
}
}
you make
double totalChange = round((totalWithTaxAndTip / 10)) * 10;
Math.round rounds a number to the nearest whole number, so as others have shown, you need to divide by 10, then multiply by 10 after rounding:
double totalChange = tenderedAmount - totalWithTaxAndTip;
double totalChangeRounded = 10 * Math.round(totalChange / 10);
Math.ceil(double) will round up a number. So what you need is something like that:
double totalChange = (int) Math.ceil(totalWithTaxAndTip / 10) * 10;
For totalWithTaxAndTip = 44.24, totalChange = 50.00
For totalWithTaxAndTip = 40.00, totalChange = 40.00
Everyone, thank you very much for helping me. I tested out everyone's solution. This is my final working code.....
double totalAmountPaid = totalWithTaxAndTip - (totalWithTaxAndTip % 10) + 10;
I tested it out using many different values and it seems to be working the way I want it to.
Again, I appreciate everyone for taking the time to help me out.
Related
the prompt says "Write a program which takes two doubles as input, then prints the sum of the numbers when they are both rounded to their nearest whole number. You may assume the double input is always positive."
what i wrote:
Scanner scan = new Scanner(System.in);
System.out.print("Please input two decimal numbers:");
double hit_1 = scan.nextDouble();
double hit_2 = scan.nextDouble();
double hit_add = (hit_1 + hit_2 + 0.5);
System.out.print("Answer: " + (int)hit_1 + " + " + (int)hit_2 + " = " + (int)hit_add);
for most decimals, it rounds fine, but what i want is for numbers like 4.5 to round to 5. right now, it rounds 4.5 to 4. i added 0.5 in an attempt to get the double to round up, but it didn't work. i'm also not allowed to use Math.round() or anything like that.
create your own round method like this.
Convert to int, then find the remainder.
If remainder >= 0.5, just add 1 to the integer. See below:
private static int round(double d){
int i = (int)d;
double remainder = d - i;
if(remainder>=0.5){
i++;
}
return i;
}
then you can use that method on your double
just need +0.5:
double a = 1.8, b = 1.2;
System.out.println((int)(a + 0.5));
System.out.println((int)(b + 0.5));
System.out.println((int)(a + 0.5) + (int)(b + 0.5));
for your code:
Scanner scan = new Scanner(System.in);
System.out.print("Please input two decimal numbers:");
double hit_1 = scan.nextDouble() + 0.5;
double hit_2 = scan.nextDouble() + 0.5;
int hit_1P2 = (int)hit_1 + (int)hit_2;
System.out.print("Answer: " + (int)hit_1 + " + " + (int)hit_2 + " = " + hit_1P2);
There was two ways where double can be rounded off to nearest integer.
a. Using typecasting to int
Example : If double holds value as 3.26, all the digits after decimal are lost.
b. Using Math.round() function - This will add 0.5 to double and rounds to nearest integer.
Example : If double holds value of 3.7, then this function will add 0.5 and rounds to 4 as nearest integer.
Similar way, if double value is 3.2, then Math.round() will add 0.5, so this would become 3.7, in this case the nearest integer is still 3
Below is sample code block for above two examples
double d = 3.5;
int typeCastInt = (int) d;
int t = (int) Math.round(d);
System.out.println(typeCastInt); //prints 3
System.out.println(t); //Prints 4
I am trying to split a number of a base then separating the two numbers to get different outputs. (Keep in mind I just edited, my answer is the solution). This is left here so people that have a similar problem can find a solution. Thank you all!
So this is the idea:
If number >= 10 && of base 10
Then give me discounted price on 10 units
if number <= 0 && not base 10
Then add the discount for the number which has 10 units in it and the remainder without the discount (let's say 100% for simplicity sake of the numbers)
So to make a practical example
If I order 25 units of x (at $1 each) and 15 units (at $1 each) of y the price will be:
x 20 units = $0
x 5 units = $5 total
y 10 units = $0
y 5 units = $5 total
This is a bit tricky and this is what I got so far:
double discountedmNI = (mNI - ((mNI/100)*10)) * mNIC;
double discountedmNIP = mNI - ((mNI/100)*10);
if(mNIC >= 10 && mNIC % 10 == 0){
System.out.println("mNI " + discountedmNIP + " " + mNIC);
System.out.println(discountedmNI);
}
else if (!mNIC % 10 == 0){
System.out.println("mNI " + mNI + mNIC);
System.out.println(mNI * mNIC);
}
I don't think I am defining separate the 10 units right
Thank you all!
I hope I understood you right. I get that you want to calculate a total price that consists of two elements: the price for non-discounted items and a price for discounted items.
// The following three values are just example assumptions.
float discountInPercent = 100.0f;
float itemsOrdered = 5004.0f;
float itemPriceNormal = 5.0f;
// Here the price for one discounted item gets calculated.
// Please remember that the discount is given in percentage.
float itemPriceDiscounted = itemPriceNormal * ((100.0f - discountInPercent) / 100.0f);
// Calculate the count of items that get discounted and those that
// will get priced normally.
float itemsDiscounted = Math.floor(itemsOrdered / 10.0f);
float itemsNotDiscounted = itemsOrdered % 10;
// Finally calculate the two elements of the total price and sum it up.
float priceDiscounted = (itemsDiscounted * itemPriceDiscounted);
float priceNormal = (itemsNotDiscounted * itemPriceNormal);
float totalPrice = priceDiscounted + priceNormal;
System.out.println("Price discounted: %.2f" + priceDiscounted);
System.out.println("Price non-discounted: %.2f" + priceNormal);
System.out.println("Price total: %.2f" + totalPrice);
EUREKA!
double discountedmNIP = mNI - ((mNI/100)*10);
int mNIC2 = (mNIC % 10);
double mNIC2disc = (mNI * mNIC2);
double discountedmNI = (mNI - ((mNI/100)*10)) * (mNIC - mNIC2);
if(mNIC >= 10){
System.out.println(discountedmNIP + " " + (mNIC - mNIC2) + " " + discountedmNI );
System.out.println(mNI + " " + mNIC2 + " " + mNIC2disc);
}
else{
System.out.print(mNI + " " + mNIC);
System.out.print(mNI * mNIC);
}
double sum = (mNI + discountedmNI + discountedRh + rH);
System.out.println('\t');
System.out.println("Total order cost " + sum);
All I need to do is to take the units % 10 which will divide the left side integer or double by the right side (left side input from user)
and will give me the remainder when I do that variable subtracted to the original variable!
Again, this small step took me a whole night to figure it out, and is simple indeed. This is for a class, and if you are in that class and you are reading (even though you might have to dig a little to find what assignment is this one), I would just like to tell you this is what's fun about programming! I am not being sarcastic I really love these type of problems!
Signed:
That foreign guy;
EUREKA again!
Enjoy!
I believe I am having a logical issue with how to develop the section of code responsible for taking the remainder and checking if I can extract change from displayed change categories.
It's designed to take a value of how much change you owe back to someone and make the most efficient set of change to give.
My current output:
The change for 328.0 Euro cents is:
1.64 € 2
1.28 € 1
0.56 € 0.50
1.4 € 0.20
0.8 € 0.10
1.6 € 0.05
1.5 € 0.02
1.0 € 0.01
Correct output:
The change for 328 Euro cents is:
1 €2
1 €1
0 €0.50
1 €0.20
0 €0.10
1 €0.05
1 €0.02
1 €0.01
I'm pretty stumped, I'd appreciate the help, thank you.
import java.util.Scanner; // Enables user input
public class Change {
private static Scanner scnr;
public static void main(String [] args) {
scnr = new Scanner(System.in);
double changeR = 0; // User input
double oneCent = 0; // Number of one cent coins
double twoCent = 0; // Number of two cent coins
double fiveCent = 0; // Number of five cent coins
double tenCent = 0; // Number of ten cent coins
double twentyCent = 0; // Number of twenty cent coins
double fiftyCent = 0; // Number of fifty cent coins
double oneEUC = 0; // Number of one Euro cent coins
double twoEUC = 0; // Number of two Euro cent coins
System.out.println("Please enter the amount of change in Euro cents to be returned (a number between 0 & 499): ");
changeR = scnr.nextInt(); // Gathers user input
System.out.println("The change for " + changeR + " Euro cents is: "); // Outputs users inputted value
twoEUC = changeR / 200;
changeR = changeR % 200;
oneEUC = changeR / 100;
changeR = changeR % 100;
fiftyCent = changeR / 50;
changeR = changeR % 50;
twentyCent = changeR / 20;
changeR = changeR % 20;
tenCent = changeR / 10;
changeR = changeR % 10;
fiveCent = changeR / 5;
changeR = changeR % 5;
twoCent = changeR / 2;
changeR = changeR % 2;
oneCent = changeR / 1;
changeR = changeR % 1;
System.out.println( twoEUC + " \u20ac" + " 2");
System.out.println( oneEUC + " \u20ac" + " 1");
System.out.println( fiftyCent + " \u20ac" + " 0.50");
System.out.println( twentyCent + " \u20ac" +" 0.20");
System.out.println( tenCent + " \u20ac" +" 0.10");
System.out.println( fiveCent + " \u20ac" +" 0.05");
System.out.println( twoCent + " \u20ac" +" 0.02");
System.out.println( oneCent + " \u20ac" +" 0.01");
return;
}
}
As is common when dealing with money¹, you need to deal with integers only.
Changing all your variables to int will give you the proper values, as integer division will make sure that 238 / 200 = 1. Instead of double division which will result in 238.0 / 200.0 = 1.19.
¹ Handling money in code (as well as real life) is a difficult problem. You need to present the output in a user readable form, so you don't want to show prices as 5.0001 € due to the problem of double imprecision, yet you don't want calculations to do "eager" rounding so the end result is off. One of the simplest ways is to take the smallest "atom", i.e. cents and deal in them only.
Why not use double or float to represent currency
I'm fairly new to Java, and I've recently written a code that calculates how much change you would need for x amount of money payed for a y priced item. It works well; my only issue is that whenever there is not any change owed in the hundredths place (ex: $4.60), it will round down to the tenths place ($4.6).
If anybody knows how to fix this, I would be very grateful. I have the code posted below.
class Main {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
double x;
double y;
double z;
System.out.print("Enter the price of the product: $");
x = scan.nextDouble();
System.out.print("Enter what you payed with: $");
y = scan.nextDouble();
z = (int)Math.round(100*(y-x));
System.out.print("Change Owed: $");
System.out.println((z)/100);
int q = (int)(z/25);
int d = (int)((z%25/10));
int n = (int)((z%25%10/5));
int p = (int)(z%25%10%5);
System.out.println("Quarters: " + q);
System.out.println("Dimes: " + d);
System.out.println("Nickels: " + n);
System.out.println("Pennies: " + p);
}
}
Edit: Thank you to everyone that answered my question! I ended up going with DecimalFormat to solve it, and now it works great.
You can call something like this:
String.format("%.2f", i);
So in your case:
...
System.out.print("Change Owed: $");
System.out.println((String.format("%.2f", z)/100));
...
String.format() is useful whenever you want to round it to certain significant figures. In this case "f" stands for float.
This behavior is expected. You do not want numbers to carry trailing zeroes.
You can use DecimalFormat for representing them as a String with a trailing zero, rounded to two digits.
Example:
DecimalFormat df = new DecimalFormat("#0.00");
double d = 4.7d;
System.out.println(df.format(d));
d = 5.678d;
System.out.println(df.format(d));
Output:
4.70
5.68
You can also add your currency sign to the DecimalFormat:
DecimalFormat df = new DecimalFormat("$#0.00");
Output with currency sign:
$4.70
$5.68
EDIT:
You can even tell DecimalFormat how to round your number by setting the RoundingMode through df.setRoundingMode(RoundingMode.UP);
The String.format() method is my personal preference. For example:
float z;
System.out.println(String.format("Change Owed: $%.2f", (float) ((z) / 100)));
%.2f will round any float ('f' stands for float) off to 2 decimal places, by changing the number before the 'f' you change how many decimal points you round to. Eg:
//3 decimal points
System.out.println(String.format("Change Owed: $%.3f", (float) ((z) / 100)));
//4 decimal points
System.out.println(String.format("Change Owed: $%.4f", (float) ((z) / 100)));
// and so forth...
You may want to do some reading into String.format() if you are starting out with Java. It is a very powerful and useful method.
From what I understand:
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
double x;
double y;
double z;
System.out.print("Enter the price of the product: $");
x = scan.nextDouble();
System.out.print("Enter what you payed with: $");
y = scan.nextDouble();
z = (int) Math.round(100 * (y - x));
System.out.println(String.format("Change Owed: $%.2f", (float) ((z) / 100)));
int q = (int) (z / 25);
int d = (int) ((z % 25 / 10));
int n = (int) ((z % 25 % 10 / 5));
int p = (int) (z % 25 % 10 % 5);
System.out.println("Quarters: " + q);
System.out.println("Dimes: " + d);
System.out.println("Nickels: " + n);
System.out.println("Pennies: " + p);
}
All the best for your future projects!
I am very new. apologies in advance for my coding. I need to print a table that shows year and then a tab over, and then the value with a next line. The value has to be in decimal form.
I have been reading and searching and mixing my code around. I have found it for 1 variable but not for two in same line. I have tried the printf, I have tried the good ol 100 / 100.0 and I either get errors or the decimal never goes to 2 places. I do not need it rounded, just with 2 spaces after. I am obviously going wrong somewhere. I would appreciate any assistance.
import java.util.Scanner;
public class Investment1 {
public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years){
double principal = 0.0;
double futureInvestmentValue = 0;
for (years = 1; years <=30; years++){
//calculate futureInvestmentValue
futureInvestmentValue = (investmentAmount * (Math.pow (1 + monthlyInterestRate, years * 12)));
System.out.print(years + "\t" + futureInvestmentValue + "\n");
}//end for
return futureInvestmentValue;
}//end futureInvestmentValue
public static void main(String[] args){
Scanner input = new Scanner (System.in);
//obtain Investment amount
System.out.print("Enter Investment amount: ");
double investmentAmount = input.nextDouble();
//obtain monthly interest rate in percentage
System.out.print("Enter annual interest rate in percentage: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = (annualInterestRate / 1200);
int years = 30;
System.out.println("Years\t" + "Future Value");
System.out.print(years + "\t");
System.out.print(years + "\t" + ((int)(futureInvestmentValue(investmentAmount, monthlyInterestRate, years))) + "\n");
}//end main
}//end Investment
You can use system.out.format():
System.out.format("%d \t %.2f", years, futureInvestmentValue);
you should read about format strings, heres a simple usage example:
System.out.println(String.format("%d %.2f",myint,myfloat));
myint will be printed as an integer (even if it's a floating point value) due to the use of the %d in the format string.
myfloat will be printed as a decimal number with 2 digits after the decimal point, thanks to the %f.2 part in the format string.