Hey so I'm trying to learn Java, and I know about floating-points not being accurate and what not, but I'm feeling blind at the moment. I know I'm doing something wrong, the computer is not wrong, but I don't know where.
I'm casting the Math returns as integers and then subtracting the specific integers value from the variable cash; when I subtract integers from floats, the float seems to lose data. My question is as follows: What is the smartest way to avoid data spoilage without slowing down my program?
<!-- language: lang-java -->
private static void calculateChange()
{
System.out.print("Please enter any amount of cash in dollars: ");
float cash = scanner.nextFloat();
int ten_dollars = (int) Math.floor(cash/10);
cash -= 10 * ten_dollars;
System.out.println(cash);
int five_dollars = (int) Math.floor(cash/5);
cash -= 5 * five_dollars;
int dollars = (int) Math.floor(cash);
cash -= dollars;
int quarters = (int) Math.floor(cash/0.25);
cash -= 0.25 * quarters;
int dimes = (int) Math.floor(cash/0.1);
cash -= 0.1 * dimes;
int nickels = (int) Math.floor(cash/0.05);
cash -= 0.05 * nickels;
int pennies = (int) Math.floor(cash/0.01);
System.out.println("This is equal to:\n" + ten_dollars + " ten dollar bills\n"
+ five_dollars + " five dollar bills\n"
+ dollars + " one dollar bills\n"
+ quarters + " quarters\n"
+ dimes + " dimes\n"
+ nickels + " nickels\n"
+ pennies + " pennies");
}
run:
Please enter any amount of cash in dollars: 135,04
5.0399933
This is equal to:
13 ten dollar bills
1 five dollar bills
0 one dollar bills
0 quarters
0 dimes
0 nickels
3 pennies
BUILD SUCCESSFUL (total time: 6 seconds)