Is there a way to use NSNumberFormatter to get the \'th\' \'st\' \'nd\' \'rd\' number endings?
EDIT:
Looks like it does not exist. Here\'s what I\'m using.
The following example demonstrates how to handle any number. It's in c# however it can easily converted to any language.
http://www.bytechaser.com/en/functions/b6yhfyxh78/convert-number-to-ordinal-like-1st-2nd-in-c-sharp.aspx
-- Swift 4 --
let num = 1
let formatter = NumberFormatter()
formatter.numberStyle = .ordinal
let day = formatter.string(from: NSNumber(value: num))
print(day!)
result - 1st
As of iOS 9
Swift 4
private var ordinalFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .ordinal
return formatter
}()
extension Int {
var ordinal: String? {
return ordinalFormatter.string(from: NSNumber(value: self))
}
}
It's probably best to have the formatter outside the extension...
There is a simple solution for this
Swift
let formatter = NumberFormatter()
formatter.numberStyle = .ordinal
let first = formatter.string(from: 1) // 1st
let second = formatter.string(from: 2) // 2nd
Obj-c
NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
numberFormatter.numberStyle = NSNumberFormatterOrdinalStyle;
NSString* first = [numberFormatter stringFromNumber:@(1)]; // 1st
NSString* second = [numberFormatter stringFromNumber:@(2)]; // 2nd
Referance: hackingwithswift.com
A clean Swift version (for English only):
func ordinal(number: Int) -> String {
if (11...13).contains(number % 100) {
return "\(number)th"
}
switch number % 10 {
case 1: return "\(number)st"
case 2: return "\(number)nd"
case 3: return "\(number)rd"
default: return "\(number)th"
}
}
Can be done as an extension for Int
:
extension Int {
func ordinal() -> String {
return "\(self)\(ordinalSuffix())"
}
func ordinalSuffix() -> String {
if (11...13).contains(self % 100) {
return "th"
}
switch self % 10 {
case 1: return "st"
case 2: return "nd"
case 3: return "rd"
default: return "th"
}
}
}
Other Swift solutions do not produce correct result and contain mistakes. I have translated CmKndy solution to Swift
extension Int {
var ordinal: String {
var suffix: String
let ones: Int = self % 10
let tens: Int = (self/10) % 10
if tens == 1 {
suffix = "th"
} else if ones == 1 {
suffix = "st"
} else if ones == 2 {
suffix = "nd"
} else if ones == 3 {
suffix = "rd"
} else {
suffix = "th"
}
return "\(self)\(suffix)"
}
}
test result: 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd