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

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

    Here's a short Int extension for the English language that also accounts for and displays negative integers correctly:

    extension Int {
        func ordinal() -> String {
            let suffix: String!
            // treat negative numbers as positive for suffix
            let number = (self < 0 ? self * -1 : self)
    
            switch number % 10 {
            case 0:
                suffix = self != 0 ? "th" : ""
            case 1:
                suffix = "st"
            case 2:
                suffix = "nd"
            case 3:
                suffix = "rd"
            default:
                suffix = "th"
            }
    
            return String(self) + suffix
        }
    }
    

提交回复
热议问题