Lion
Lion

Reputation: 872

How to deal with separator format in Swift 3

Having a great deal of trouble finding a way to (Formating) remove comma and if no comma found then leave as it is.

What I am hoping to achieve is taking the result of a distance and displaying it in a Label so that the format is:

4589.163

instead of

4,589.163

If no comma separator found then leave it as it is

479.996

My code:

if tempDistanceString.contains(",") {
       let newString = tempDistanceString.replacingOccurrences(of: ",", with: "")
}

I'm looking for Formatter if supportable to my requirement.

Any help would be greatly appreciated.

Upvotes: 0

Views: 1042

Answers (2)

Danny
Danny

Reputation: 4079

You can use numberFormatter with property usesGroupingSeparator set to false

For example:

let formatter = LengthFormatter()
formatter.numberFormatter.usesGroupingSeparator = false

Upvotes: 1

Jaydeep Vora
Jaydeep Vora

Reputation: 6213

Swift 3.1

Just replace occurrences of comma with blank string.

let aString = "4,589.163"
let newString = aString.replacingOccurrences(of: ",", with: "")

Upvotes: 2

Related Questions