John Hubler
John Hubler

Reputation: 909

Running operations on numbers with commas in Swift3

If I have a number that is over 1,000, so that it has a comma in it, how can I either strip out the commas, or convert this number into a Double, so that I can run mathematical operations on it?

Right now, I have the following code:

let oldBFTally: Double = Double(plBFTally.text!)!
let newBFTally: Double = round(1000 * (rawValue + oldBFTally) / 1000)

This code works great, as long as the number is under 1000. But, being that I am formatting the number as text, so that it has commas (ie: 1,234.56), whenever I try to run that first line, it errors out, saying: "fatal error: unexpectedly found nil while unwrapping an Optional value".

Any ideas what I can do to navigate around this issue?

Upvotes: 0

Views: 71

Answers (2)

Paulw11
Paulw11

Reputation: 114965

@Jim is correct; your text field should simply contain a textual representation of your internal variable, so you shouldn't need to convert back to a double, but for reference, you can use a NumberFormatter

import Foundation

let formatter = NumberFormatter()

formatter.numberStyle = .decimal

if let number = formattter.number(from:"10,000") {
    print(number.doubleValue)
}

Upvotes: 1

Jim
Jim

Reputation: 73966

But, being that I am formatting the number as text, so that it has commas (ie: 1,234.56)

You're trying to tackle the problem in the wrong way. If you're generating this string in the first place, then if you want to perform mathematical operations on the number, you shouldn't be displaying it as a string in the UI, then trying to go backwards from the UI back to a number. That's misusing your presentation layer as your data model.

Instead of trying to go back and forth between the UI, use the original value you generated the string from.

Upvotes: 1

Related Questions