Reputation: 765
I am trying to convert a String into a Double value in Swift. After doing a lot of research, I believe that this would be the best method to turn my string to an Double. But now I am getting an error that I have no idea of how to fix.
var purchaseAmount: Double = 200
var cashTendered: Double = 425.45
var changeRequired: Double = 0
var currencyValues = ["100", "50", "20", "10", "5", "2", "1", "0.50", "0.20", "0.10", "0.05"]
import Cocoa
if cashTendered < purchaseAmount {
println("Not enough cash tendered")
} else {
changeRequired = cashTendered - purchaseAmount
for currency in currencyValues {
var doubleCurrency = (currency as NSString).doubleValue
var amountOfCurrency = changeRequired / doubleCurrency
amountOfCurrency = floor(amountOfCurrency)
changeRequired = changeRequired - (amountOfCurrency * currency)
changeRequired = round(changeRequired * 100)/100
println("$\(currency) X \(Int(amountOfCurrency))")
}
}
Here is the error:
What do I have to do to solve this problem?
Upvotes: 0
Views: 178
Reputation: 23053
First of all initialise String
array like below:
let currencyValues : [String] = ["100", "50", "20", "10", "5", "2", "1", "0.50", "0.20", "0.10", "0.05"]
However it is not required type declaration because of Swift has vital feature Type Interface. But most of the practice it is good to define type while working with array.
And about converting string to double you can use below code:
for currency : String in currencyValues {
let doubleCurrency = NSNumberFormatter().numberFromString(currency)!.doubleValue
print(doubleCurrency)
}
Upvotes: 2
Reputation: 3352
Posting code would be easier to look at than an image, but if all else fails there is NSNumberFormatter. Other advantage of NSNumberFormatter would allow you to convert both directions and get nice output for things like currency.
Upvotes: 0