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

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

    It's quite simple in English. Here's a swift extension:

    extension Int {
        var ordinal: String {
            get {
                var suffix = "th"
                switch self % 10 {
                    case 1:
                        suffix = "st"
                    case 2:
                        suffix = "nd"
                    case 3:
                        suffix = "rd"
                    default: ()
                }
                if 10 < (self % 100) && (self % 100) < 20 {
                    suffix = "th"
                }
                return String(self) + suffix
            }
        }
    }
    

    Then call something like:

        cell.label_position.text = (path.row + 1).ordinal
    

提交回复
热议问题