Working on a simple java program that should only accept an input that is in .05 cent increments. When attempting to use the mod operator for data validation, I am getting some weird, unexpected results:
public static void takePayment(double itemCost){
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(itemCost);
Scanner input = new Scanner(System.in);
System.out.println("Please insert $" + df.format(itemCost) + " into the machine");
System.out.println("Type the amount you are inserting into the machine.");
System.out.print("$");
if (!input.hasNextDouble()){
System.out.println("Please enter the amount inserted in X.XX format");
takePayment(itemCost);
}
double amtInsert = 0;
amtInsert = input.nextDouble();
double remainder = 0;
remainder = amtInsert %(0.05);
System.out.println(remainder);
if (remainder == 0)
{
System.out.println("works");
}else{
System.out.println("Invalid amount inserted, this machine only accepts Nickels, Dimes, Quarters, "
+ "1 dollar bills, and 5 dollar bills ");
takePayment(itemCost);
}
}
If a dollar amount such as 1.25 is entered into the function, it returns:
Please insert $1.25 into the machine
Type the amount you are inserting into the machine.
$1.25
0.04999999999999993
Invalid amount inserted, this machine only accepts Nickels, Dimes, Quarters, 1 dollar bills, and 5 dollar bills.
Can someone explain why (1.25 % .05) = 0.04999999999999993
Keep in mind while reading my code that I haven't written the rest of the validation, I am only concerned with the modulus at the moment