tentmaking
tentmaking

Reputation: 2146

Swift String to Int Always Returns nil

I am trying to convert a String to an Int. Seems simple enough, but for somer reason it is always returning nil.

I'm just writing a simple extension to convert dollars to cents:

func dollarsToCents() -> Int {
    var temp = self;
    temp = temp.replacingOccurrences(of: "$", with: "")
    temp = temp.replacingOccurrences(of: ",", with: "")

    if let number = Int(temp) {
        return number*100
    }

    return 0
}

I have temp set to "$250.89". number is always nil. No matter how I approach converting temp to an Int it is always nil. Anyone know what I'm doing wrong?

Upvotes: 2

Views: 2104

Answers (2)

Hews
Hews

Reputation: 581

Just adding this for the bizarre edge-case that I just encountered - be sure there aren't any whitespaces either trailing or leading in your string when converting to Int from String.

Eg.

for date in next_thirty_days {
    let date_buffer: String = date.description[8...9]
    date_list.append(Int(date_buffer)!)
}

This will fail if the value for date_buffer has a leading or trailing white-space.

Another edge-case is that there's a leading 0 in the string variable, eg. 07.

Hope it helps :)

Upvotes: 0

Robert Dresler
Robert Dresler

Reputation: 11140

Problem is, that string "250.89" (after removing currency symbol) can't be converted to Int because 250.89 isn't integer. So fix your code by converting it to Double

func dollarsToCents() -> Int {
    var temp = self
    temp.removeAll { "$,".contains($0) }
    //temp = temp.replacingOccurrences(of: "[$,]", with: "", options: .regularExpression)
    return Int(((Double(temp) ?? 0) * 100).rounded())
}

or if your "number" always have two decimal places

func dollarsToCents() -> Int {
    var temp = self
    temp.removeAll { !("0"..."9" ~= $0) }
    return Int(temp) ?? 0
}

But I think solution is much easier. Your goal should be saving price value as number (Double,...). Then you don't have to convert String to Double and you can just multiply your number. Then when you need to add currency symbol, just convert your value to String and add $ or use NumberFormatter

let price = 250.89
let formattedPrice = "$\(price)" // $250.89

let price = 250.89
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = "USD"
let formattedPrice = formatter.string(from: price as NSNumber)! // $250.89

Upvotes: 6

Related Questions