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

前端 未结 20 1273
粉色の甜心
粉色の甜心 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:30

    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

提交回复
热议问题