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
Related
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 am having a hard time understanding how to convert amounts such as $1.17 into this output:
1 dollar,
1 dime,
1 nickel,
2 pennies.
I need to use if statements which I can figure out but, the problem i am having is trying to get the change amounts to display correctly. Here is my code. I`m a visual learner so if you start me in the right direction that would be helpful.
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an amount in double, for example 11.56: " );
double number = input.nextDouble();
System.out.println("Your amount " + number + " consists of ");
int Dollars = (int) (number);
int Quarters = Dollars / 25;
if (number == 1) {
System.out.print("1 dollar ");
}
else if (number > 1) {
System.out.print((int)Dollars + " dollars ");
}
if (number == 0) {
System.out.println("");
}
System.out.print( Quarters + " Quarters ");
}
}
You will probably want to use the modulus operator %. It is used with 2 numbers and returns the remainder of a divided by b where a is the left hand assignment and b is the right hand represented like a%b.
Example:
11%2=1 explanation: 5*2 = 10, 11-10 = 1
.66%.25=.16 explanation: 2*.25 = .5, .66-.5=.16
Start with a simple problem where you only have 2 types of coins, say 8¢ or $0.08.
double monies = .08;
int numNickles = (int)(monies/.05) = 1 // one nickle
monies = monies % .05; // or you can write as monies %=.05;
// monies value should now be .03
int numPennies = (int)(monies/.01) = 3 // three pennies
A much simpler approach than using modulus is to calculate the units of measurement in top-down fashion (from the highest to the lowest) and keep deducting them from the total already converted into the lowest unit.
A lot of libraries use this approach with units of time as well i.e. converting a time span into hours, minutes and seconds. Here's the same approach for currency. I've added inline comments to explain the code as best as possible.
// Scan the amount
Scanner scanner = new Scanner(System.in);
System.out.print("Enter amount: ");
double amount = scanner.nextDouble();
scanner.close();
// convert into cents
int cents = (int) (amount * 100);
// get dollars
int dollars = cents/100;
// cents left after dollars
cents = cents - dollars*100;
// get quarters
int quaters = cents/25;
// cents left after quarters
cents = cents - quaters*25;
// get dimes
int dimes = cents/10;
// cents left after dimes
cents = cents - dimes*10;
// get nickels
int nickels = cents/5;
// cents left after nickels
cents = cents - nickels*5;
// leftover cents are pennies
int pennies = cents;
Now, just build the output message with a StringBuilder as
StringBuilder msg = new StringBuilder("You have:");
if (dollars > 0) {
msg.append(" ").append(dollars).append(" dollar").append(dollars > 1 ? "s" : "");
}
if (quaters > 0) {
msg.append(" ").append(quaters).append(" quarter").append(quaters > 1 ? "s" : "");
}
if (dimes > 0) {
msg.append(" ").append(dimes).append(" dime").append(dimes > 1 ? "s" : "");
}
if (nickels > 0) {
msg.append(" ").append(nickels).append(" nickel").append(nickels > 1 ? "s" : "");
}
if (pennies > 0) {
msg.append(" ").append(pennies).append(" pennie").append(pennies > 1 ? "s" : "");
}
System.out.println(msg);
Output :
Enter amount: 1.17
You have: 1 dollar 1 dime 1 nickel 2 pennies
Enter amount: 12.99
You have: 12 dollars 3 quarters 2 dimes 4 pennies
I got the dollars to work but now I can`t figure out how to display the quarters, dimes, nickels, and pennies correctly. Technically they show up but my professor wants $1.35 to show up as 1 dollar 1 quarter and 1 dime. But, mine shows up as 1 dollars 5 Quarters 13 Dimes 27 Nickels 135 Pennies. Here is my code:
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an amount in double, for example 11.56: " );
double number = input.nextDouble();
System.out.println("Your amount " + number + " consists of ");
int remainingamount = (int)(number*100);
int Quarters = remainingamount/25;
int Dimes = remainingamount/10;
int Nickels = remainingamount/5;
int Pennies = remainingamount;
if (number == 1) {
System.out.print("1 dollar ");
}
else if (number > 1) {
System.out.print((int)number + " dollars ");
}
if (number == 0) {
System.out.println("");
}
System.out.print(Quarters + " Quarters " + Dimes + " Dimes " + Nickels + " Nickels " + Pennies + " Pennies");
}
}
For each different coin you calculate, you need to remove this from the remaining amount. Such as (untested):
int Dollars = (int)number;
int remainingamount = (int)((number-Dollars)*100);
int Quarters = remainingamount/25;
remainingamount -= Quaters * 25;
int Dimes = remainingamount/10;
remainingamount -= Dimes * 10
int Nickels = remainingamount/5;
remainingamount -= Nickels * 5
int Pennies = remainingamount;
Since you're using Java, have you tried JSR 354?
See JavaMoney.org or the JSR 354 Detail page at JCP.org It offers standard API for the conversion of monetary units and default exchange rate providers by the IMF or European Central Bank.
I have tried many ways like math.Round and making them doubles and ints but i have no idea why and where it rounds down to 2 cents at the end. When i purchase 32.27 and pay with 36 the answer is 3 dollars 2 quarters 2 dimes 2 cents.
here is my code:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Purchase: ");
double purchase = input.nextDouble();
System.out.print("Payment: ");
double amountGiven = input.nextDouble();
int remainingAmount = (int) ((amountGiven - purchase) * 100);
int numOfDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
int numOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
int numOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
int numOfPennies = remainingAmount;
System.out.println("Given $ " + amountGiven + " for a purchase of $ " +
purchase + " we need " + numOfDollars + " dollars " + numOfQuarters +
" quarters " + numOfDimes + " dimes " +
numOfPennies + " cents ");
}
}
If you run this code, you'll see where your problem is:
final double purchase = 32.27;
System.out.println("Purchase: " + new BigDecimal(purchase));
final double diff = 36 - purchase;
System.out.println("Difference: " + new BigDecimal(diff));
System.out.println("Cent difference: " + (int)(100*diff));
The output will be
Purchase: 32.27000000000000312638803734444081783294677734375
Difference: 3.72999999999999687361196265555918216705322265625
Cent difference: 372
So you can see that your trouble starts right off the bat: the decimal value 32.27 is represented by the nearest double value, which is slightly larger. The difference is then slightly less, which after truncation drops a whole cent.
Lesson: don't parse the input into a double, but into a BigDecimal.
This happens, because the amount cannot be represented exactly as a double. When you convert to an int it gets truncated.
The change amount in cents is 372.99999999999955 if you print it with 14 decimals.
Either use BigDecimal or a custom Currency type that only uses Integer or int to do calculations.
Calculations of this type should never use primitive types. Always use BigDecimal.
You can't do division that results in remainders on integer types without losing precision
double d1 = 32.27;
double d2 = 36;
int i1 = (int) (d1 * 100);
int i2 = (int) (d2 * 100);
int rad = (int) ((d1 - d2 ) * 100);
int rai = i1 - i2;
double rdd = (double)rai / 100; // <- this is what you are expecting
int ndi = rai / 100;
// ^ this is what you are getting
// int / int == double which gets silently truncated
System.out.println("i1 = " + i1);
System.out.println("i2 = " + i2);
System.out.println("rad = " + rad);
System.out.println("rai = " + rai);
System.out.println("rdd = " + rdd); // mostly accurate in this case
System.out.println("ndi = " + ndi); // truncated
Ouputs
i1 = 3227
i2 = 3600
rad = -372
rai = -373
rdd = -3.73
ndi = -3
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.