gvuksic gvuksic - 6 months ago 28
iOS Question

NSNumberFormatter grouping

I would like to format string with numbers to look like this:

XX XX XX
(e.g.
12 34 56
)

I'm using
NSNumberFormatter
with grouping separator:

let formatter = NSNumberFormatter()
formatter.usesGroupingSeparator = true
formatter.groupingSize = 2
formatter.groupingSeparator = " "
if let number = Int(theText.stringByReplacingOccurrencesOfString(" ", withString: "")) {
let numberToFormat = NSNumber(integer:number)
textField.text = formatter.stringFromNumber(numberToFormat)
}


This will work fine, if you enter number
123456
- it is formatted to
12 34 56


I use this inside
shouldChangeCharactersInRange
method so it should format number as you type. Grouping separator defines numbers are grouped by
groupingSize
value from right side, so when you type in
123456
this is how text changes:

1
12
1 23
12 34
1 23 45
12 34 45


and I would like to format it as following:

1
12
12 3
12 34
12 34 5
12 34 56


Is it possible to define from which side grouping separator groups numbers?

Answer

Not sure if you have to covert to Int, how about add a "0" at the end? Then remove the last "0".

let formatter = NSNumberFormatter()
formatter.usesGroupingSeparator = true
formatter.groupingSize = 2
formatter.groupingSeparator = " "

var str = "12345"
if str.characters.count % 2 != 0 {
    str += "0"
}
if let number = Int(str.stringByReplacingOccurrencesOfString(" ", withString: "")) {
    let numberToFormat = NSNumber(integer:number)
    formatter.stringFromNumber(numberToFormat)
}

Another solution:

let string = "12345"

var results = [String]()
for index in 0 ..< string.characters.count-1 {
    if index % 2 == 0 {
        let range = NSRange(location: index, length: 2)
        results.append((string as NSString).substringWithRange(range))
    }
}

if string.characters.count % 2 != 0 {
    let last = (string as NSString).substringFromIndex(string.characters.count-1)
    results.append(last)
}