Reputation: 35
(COMPLETE newbie here). I've got an extra sheet with simple exercises to complete. One of the exercises says to write a program where user can input a random amount of money and the program tells the user how many euros, 50 cents, 20 cents, 10 cents, 5 cents, 2 cents and 1 cents are needed to make up the amount entered. I try to use the modulus to get the amount of cents needed,
My question is how do I get my program to calculate the number of CENTS needed? Everytime I use division operator to get the number of 50 cents needed on the remainder of the amount (ex. 0.60) it rounds the double up giving me 2 as output.
Scanner keyboard = new Scanner(System.in);
System.out.print("Input money recieved: ");
double recieve = keyboard.nextDouble();
double cents = recieve * 100;
int centsTotal = (int)cents;
System.out.print("Cents in total " + centsTotal);
int notes = centsTotal / 100;
System.out.print("\nEuros: " + notes);
double remain = recieve % notes;
System.out.printf("\nRemain: %.2f",remain);
double remain2 = remain / 0.5;
System.out.println("\nTest: ",remain2);
My output is:
Input money recieved: 45,78
Cents in total 4578
Euros: 45
Remain: 0,78
Test: 1.5600000000000023
Upvotes: 2
Views: 1769
Reputation: 6014
One way is maybe a little brutal, but memory efficient (create no new object or variables). Simply cast your double
to int
to round down.
public class RoundingTest {
public static void main(String[] args) {
double num = 1.56;
System.out.println("Test: " + (int)num);
}
}
Outputs:
Test: 1
This also allows you to keep your original double untouched for further calculation if needed.
Upvotes: 0
Reputation: 1975
You can cheat by using the Math.round()
function like so:
double roundOff = Math.round(valueToRound * 100.0) / 100.0;
This ensures that you keep the value as a double, which allows you to do further operations on it if necessary.
Upvotes: 1