6

I have this string:

Some text: $ 12.3 9

I want to get as a result: 12.39

I have found examples on how to keep only numbers, but here I am wanting to keep the decimal point "."

What's a good way to do this in Swift?

zumzum
  • 17,984
  • 26
  • 111
  • 172
  • Have you tried adapting one example to your use case? – luk2302 Jan 17 '16 at 18:07
  • 2
    Note that as per your question, the result should not include the `$` character. Or do you want it to? – dfrib Jan 17 '16 at 18:11
  • http://stackoverflow.com/a/29783546/2303865 to allow the user to input only digits with two fixed fraction digits and automatically format it. – Leo Dabus Jan 17 '16 at 18:18

3 Answers3

13

This should work (it's a general approach to filtering on a set of characters) :

[EDIT] simplified and adjusted to Swift3

[EDIT] adjusted to Swift4

let text     = "$ 123 . 34 .876"
let decimals = Set("0123456789.")
var filtered = String( text.filter{decimals.contains($0)} )

If you need to ignore anything past the second decimal point add this :

filtered = filtered.components(separatedBy:".")    // separate on decimal point
                   .prefix(2)                      // only keep first two parts
                   .joined(separator:".")          // put parts back together
Alain T.
  • 40,517
  • 4
  • 31
  • 51
4

Easiest and simplest reusable way: you can use this regex replacement option. This replaces all characters except 0 to 9 and dot (.) .


let yourString = "$123. 34"
//pattern says except digits and dot.
let pattern = "[^0-9.]"
do {
    let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)

    //replace all not required characters with empty string ""
    let string_With_Just_Numbers_You_Need = regex.stringByReplacingMatchesInString(yourString, options: NSMatchingOptions.WithTransparentBounds, range: NSMakeRange(0, yourString.characters.count), withTemplate: "")

    //your number converted to Double
    let convertedToDouble = Double(string_With_Just_Numbers_You_Need)
} catch {
    print("Cant convert")
}
pswaminathan
  • 8,734
  • 1
  • 20
  • 27
Bibek
  • 3,689
  • 3
  • 19
  • 28
0

One possible solution to the question follows below. If you're working with text fields and currency, however, I suggest you take a look at the thread Leo Dabus linked to.

extension String {
    func filterByString(myFilter: String) -> String {
        return String(self.characters.filter {
            myFilter.containsString(String($0))
            })
    }
}

var a = "$ 12.3 9"
let myFilter = "0123456789.$"
print(a.filterByString(myFilter)) // $12.39
dfrib
  • 70,367
  • 12
  • 127
  • 192