Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift string strip all characters but numbers and decimal point?

Tags:

string

swift

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?

like image 279
zumzum Avatar asked Jan 17 '16 18:01

zumzum


1 Answers

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
like image 51
Alain T. Avatar answered Nov 09 '22 07:11

Alain T.