I'm trying to remove all the whitespaces from the NSNumberFormatter string. It seems it adds Unicode 160 as a whitespace instead of Unicode 32 and then String's stringByReplacingOccurrencesOfString doesn't work. Is this correct behavior and how should I remove the whitespaces?
let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "fi")
formatter.numberStyle = .CurrencyStyle
formatter.currencyCode = "EUR"
formatter.currencySymbol = ""
let value = formatter.stringFromNumber(1234) ?? "" //"1 234,00 "
let trimmed = value.stringByReplacingOccurrencesOfString(" ", withString: "") // "1 234,00 "
let chars = value.utf16.map { $0 }
chars // [49, 160, 50, 51, 52, 44, 48, 48, 160]
The value you’re seeing is U+00A0 NO-BREAK SPACE. NSNumberFormatter uses this deliberately because word wrapping at a thousands separator would be very confusing.
To achieve your goal you should look at
+[NSCharacterSet whitespaceCharacterSet]
. There are various ways you can use this to search and replace for whitespace but here’s a one-line drop-in replacement.
let trimmed = value.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).joinWithSeparator("")
Finally, concerning your goal you wrote:
I'm trying to remove all the whitespaces from the NSNumberFormatter string.
This is worrying from a localisation standpoint. I don’t have any concrete examples but, given the wide world of locale-specific behaviour, my guess is that there will be at least one place where removing whitespace from a formatted number causes semantic differences.
Share and Enjoy
—
Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"