NSNumberFormatter and 'th' 'st' 'nd' 'rd' (ordinal) number endings

前端 未结 20 1307
粉色の甜心
粉色の甜心 2020-12-03 00:38

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.

20条回答
  •  没有蜡笔的小新
    2020-12-03 01:29

    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"
            }
        }
    
    }
    

提交回复
热议问题