-2

I wrote a basic program for calculating money. If I switch the data type of the functions to a float. The count for pennies is incorrect if I set my initial value to 16.16. If I switch it to a double it corrects it. I am not sure why this is happening. I know that a double is more precise but I didn't think that would affect my program.

import UIKit

func moneyCounter(initialValue: Double) -> Array<Any> {
    var money = initialValue
    func countsTypesOfMoney(moneyValue: Double) -> String {
        var moneyTypeAmmount = 0
        while money >= moneyValue {
           money -= moneyValue
           moneyTypeAmmount += 1
        }
    return String(moneyTypeAmmount)
    }  
return ["$" + String(initialValue) + " = " + countsTypesOfMoney(moneyValue: 1.00) + "         
dollars + " + countsTypesOfMoney(moneyValue: 0.25) + " quarters + " +    
countsTypesOfMoney(moneyValue: 0.10) + " dimes + " + countsTypesOfMoney(moneyValue: 0.05) +
" nickels + " + countsTypesOfMoney(moneyValue: 0.01) + " pennies"]
}
print(moneyCounter(initialValue: 16.16))

1 Answers1

0

Using a float or a double is really a bad choice when you are counting individual items. Both float's and double's can be imprecise. I've seen times where I had a value of 0.8, i subtracted 0.2 from it and I got 0.60000002. You could also get 0.59999998, or some similar slightly off value, which if you are truncating, like you do in your countTypesOfMoney method, you would go from 60 pennies to 59, just because of a rounding error.

It would be much better to just send pennies or cents and count from that.

import UIKit

func moneyCounter(initialCents: Int) -> Array<Any> {
    var money = initialValue
    func countsTypesOfMoney(moneyValue: Int) -> String {
        var moneyTypeAmount = 0
        while money >= moneyValue {
           money -= moneyValue
           moneyTypeAmount += 1
        }
    return String(moneyTypeAmount)
    }  
return ["$" + String(initialValue) + " = " + countsTypesOfMoney(moneyValue: 1.00) + "         
dollars + " + countsTypesOfMoney(moneyValue: 0.25) + " quarters + " +    
countsTypesOfMoney(moneyValue: 0.10) + " dimes + " + countsTypesOfMoney(moneyValue: 0.05) +
" nickels + " + countsTypesOfMoney(moneyValue: 0.01) + " pennies"]
print(moneyCounter(initialCents: 1616))

If you are required to input a decimal version, such as from a user input, I'd bring in a string and parse it for the decimal and convert it to pennies. If this is for some goofy school assignment, and you need to keep using floats or doubles like this, you should round to the nearest penny at the end.

Also I would use the % function for getting the different denominations.

HalR
  • 11,411
  • 5
  • 48
  • 80