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

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

    Here's a Swift solution that cycles through the user's preferred languages until it finds one with known rules (which are pretty easy to add) for ordinal numbers:

        extension Int {
            var localizedOrdinal: String {
    
                func ordinalSuffix(int: Int) -> String {
                    for language in NSLocale.preferredLanguages() as [String] {
    
                    switch language {
                        case let l where l.hasPrefix("it"):
                            return "°"
                        case let l where l.hasPrefix("en"):
                            switch int {
                            case let x where x != 11 && x % 10 == 1:
                                return "st"
                            case let x where x != 12 && x % 10 == 2:
                                return "nd"
                            case let x where x != 13 && x % 10 == 3:
                                return "rd"
                            default:
                                return "th"
                            }
                        default:
                            break
                        }
                    }
    
                    return ""
                }
    
                return "\(self)" + ordinalSuffix(self)
            }
        }
    

提交回复
热议问题