NSNumberFormatter和'th''st''nd''rd'(序数)数字结尾

时间:2010-07-22 20:04:53

标签: ios objective-c nsnumberformatter

有没有办法使用NSNumberFormatter来获得'th''st''nd''rd'数字结尾?

编辑:

看起来它不存在。这就是我正在使用的。

+(NSString*)ordinalNumberFormat:(NSInteger)num{
    NSString *ending;

    int ones = num % 10;
    int tens = floor(num / 10);
    tens = tens % 10;
    if(tens == 1){
        ending = @"th";
    }else {
        switch (ones) {
            case 1:
                ending = @"st";
                break;
            case 2:
                ending = @"nd";
                break;
            case 3:
                ending = @"rd";
                break;
            default:
                ending = @"th";
                break;
        }
    }
    return [NSString stringWithFormat:@"%d%@", num, ending];
}

改编自nickf的答案 Is there an easy way in .NET to get "st", "nd", "rd" and "th" endings for numbers?

20 个答案:

答案 0 :(得分:33)

从iOS 9开始,正确的方法是:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterOrdinalStyle;

NSLog(@"%@", [numberFormatter stringFromNumber:@(1)]); // 1st
NSLog(@"%@", [numberFormatter stringFromNumber:@(2)]); // 2nd
NSLog(@"%@", [numberFormatter stringFromNumber:@(3)]); // 3rd, etc.

可替换地:

NSLog(@"%@", [NSString localizedStringFromNumber:@(1)
                                     numberStyle:NSNumberFormatterOrdinalStyle]); // 1st

答案 1 :(得分:22)

这是一种方法(英语)的技巧。感谢nickf https://stackoverflow.com/a/69284/1208690获取PHP中的原始代码,我只是将其改编为objective C: -

-(NSString *) addSuffixToNumber:(int) number
{
    NSString *suffix;
    int ones = number % 10;
    int tens = (number/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";
    }

    NSString * completeAsString = [NSString stringWithFormat:@"%d%@", number, suffix];
    return completeAsString;
}

答案 2 :(得分:15)

其他Swift解决方案无法产生正确的结果并包含错误。 我已将CmKndy解决方案翻译成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)"
    }

}

测试结果: 第0 1 第2 第3 第四 第5 第6 7日 第八 9日 第10 第11 第12 第13 第14 第15 第16 17 18 19 20 21 第22 23

答案 3 :(得分:14)

由于问题需要一个数字格式器,这是我做的一个粗略的。

//
//  OrdinalNumberFormatter.h
//

#import <Foundation/Foundation.h>


@interface OrdinalNumberFormatter : NSNumberFormatter {

}

@end

和实施:

//
//  OrdinalNumberFormatter.m
//

#import "OrdinalNumberFormatter.h"


@implementation OrdinalNumberFormatter

- (BOOL)getObjectValue:(id *)anObject forString:(NSString *)string errorDescription:(NSString **)error {
    NSInteger integerNumber;
    NSScanner *scanner;
    BOOL isSuccessful = NO;
    NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];

    scanner = [NSScanner scannerWithString:string];
    [scanner setCaseSensitive:NO];
    [scanner setCharactersToBeSkipped:letters];

    if ([scanner scanInteger:&integerNumber]){
        isSuccessful = YES;
        if (anObject) {
            *anObject = [NSNumber numberWithInteger:integerNumber];
        }
    } else {
        if (error) {
            *error = [NSString stringWithFormat:@"Unable to create number from %@", string];
        }
    }

    return isSuccessful;
}

- (NSString *)stringForObjectValue:(id)anObject {
    if (![anObject isKindOfClass:[NSNumber class]]) {
        return nil;
    }

    NSString *strRep = [anObject stringValue];
    NSString *lastDigit = [strRep substringFromIndex:([strRep length]-1)];

    NSString *ordinal;


    if ([strRep isEqualToString:@"11"] || [strRep isEqualToString:@"12"] || [strRep isEqualToString:@"13"]) {
        ordinal = @"th";
    } else if ([lastDigit isEqualToString:@"1"]) {
        ordinal = @"st";
    } else if ([lastDigit isEqualToString:@"2"]) {
        ordinal = @"nd";
    } else if ([lastDigit isEqualToString:@"3"]) {
        ordinal = @"rd";
    } else {
        ordinal = @"th";
    }

    return [NSString stringWithFormat:@"%@%@", strRep, ordinal];
}

@end

将其实例化为Interface Builder对象,并将Text Field的格式化程序出口附加到其中。为了更好地控制(例如设置最大值和最小值,您应该创建格式化程序的实例,根据需要设置属性,并使用它的setFormatter:方法将其附加到文本字段。

您可以download the class from GitHub(包括示例项目)

答案 4 :(得分:13)

从iOS 9开始

Swift 4

private var ordinalFormatter: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.numberStyle = .ordinal
    return formatter
}()

extension Int {
    var ordinal: String? {
        return ordinalFormatter.string(from: NSNumber(value: self))
    }
}

最好将格式化程序放在扩展名之外......

答案 5 :(得分:6)

英语很简单。这是一个快速扩展:

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

然后打电话给:

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

答案 6 :(得分:5)

只需添加另一个实现作为类方法。直到我从php中的一个例子实现了这个问题后才发现这个问题。

+ (NSString *)buildRankString:(NSNumber *)rank
{
    NSString *suffix = nil;
    int rankInt = [rank intValue];
    int ones = rankInt % 10;
    int tens = floor(rankInt / 10);
    tens = tens % 10;
    if (tens == 1) {
        suffix = @"th";
    } else {
        switch (ones) {
            case 1 : suffix = @"st"; break;
            case 2 : suffix = @"nd"; break;
            case 3 : suffix = @"rd"; break;
            default : suffix = @"th";
        }
    }
    NSString *rankString = [NSString stringWithFormat:@"%@%@", rank, suffix];
    return rankString;
}

答案 7 :(得分:5)

这是一个适用于所有整数类型的紧凑Swift扩展:

extension IntegerType {
    func ordinalString() -> String {
        switch self % 10 {
        case 1...3 where 11...13 ~= self % 100: return "\(self)" + "th"
        case 1:    return "\(self)" + "st"
        case 2:    return "\(self)" + "nd"
        case 3:    return "\(self)" + "rd"
        default:   return "\(self)" + "th"
        }
    }
}

使用示例:

let numbers = (0...30).map { $0.ordinalString() }
print(numbers.joinWithSeparator(", "))

输出:

  第0,第1,第2,第3,第4,第5,第6,第7,第8,第9,第10,第11,第12,第13,第14,第15,第16,第17,第18,第19,第20,第21,第22,第23 ,24日,25日,26日,27日,28日,29日,30日

答案 8 :(得分:4)

- Swift 4 -

     let num = 1
     let formatter = NumberFormatter()
     formatter.numberStyle = .ordinal
     let day = formatter.string(from: NSNumber(value: num))

     print(day!)
     result - 1st

答案 9 :(得分:3)

我不知道这种能力。但是,你可以自己做这件事。在英语中,序数(th,st,nd,rd等)有一个非常简单的模式:

如果号码以:=&gt;结尾使用:

  • 0 =&gt;个
  • 1 =&gt; ST
  • 2 =&gt; ND
  • 3 =&gt; RD
  • 4 =&gt;个
  • 5 =&gt;个
  • 6 =&gt;个
  • 7 =&gt;个
  • 8 =&gt;个
  • 9 =&gt;个
  • 11 =&gt;个
  • 12 =&gt;个
  • 13 =&gt;个

这不会为你说出这个词,但它会让你做一些像:“42nd”,“1,340,697th”等等。

如果您需要本地化,这会变得更加复杂。

答案 10 :(得分:3)

一个干净的Swift版本(仅限英文版):

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

可以作为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"
        }
    }

}

答案 11 :(得分:2)

以下示例演示如何处理任何数字。它在c#中,但它可以很容易地转换为任何语言。

http://www.bytechaser.com/en/functions/b6yhfyxh78/convert-number-to-ordinal-like-1st-2nd-in-c-sharp.aspx

答案 12 :(得分:2)

这个

有一个简单的解决方案
let formatter = NumberFormatter()
formatter.numberStyle = .ordinal
let first = formatter.string(from: 1) // 1st
let second = formatter.string(from: 2) // 2nd

Referance:hackingwithswift.com

答案 13 :(得分:1)

这会将日期转换为字符串,并在日期中添加序号。您可以通过更改 NSDateFormatter 对象

来修改日期格式
-(NSString*) getOrdinalDateString:(NSDate*)date
{
    NSString* string=@"";
    NSDateComponents *components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay fromDate:date];

    if(components.day == 1 || components.day == 21 || components.day == 31)
        string = @"st";

    else if (components.day == 2 || components.day == 22)
        string = @"nd";

    else if (components.day == 3 || components.day == 23)
        string = @"rd";

    else
        string = @"th";


    NSDateFormatter *dateFormatte = [[NSDateFormatter alloc] init];
    [dateFormatte setFormatterBehavior:NSDateFormatterBehavior10_4];
    [dateFormatte setDateFormat:[NSString stringWithFormat:@"d'%@' MMMM yyyy",string]];

    NSString *dateString = [dateFormatte stringFromDate:date];
    return dateString;
}

答案 14 :(得分:0)

这是英语的简短Int扩展,它也能正确地解释和显示负整数:

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

答案 15 :(得分:0)

这里的许多解决方案都不能处理更高的数字,例如112.这是一种简单的方法。

for(int i=0;i<1000;i++){
    int n = i;
    NSString* ordinal = @"th";
    if(n%10==1 && n%100!=11) ordinal = @"st";
    if(n%10==2 && n%100!=12) ordinal = @"nd";
    if(n%10==3 && n%100!=13) ordinal = @"rd";
    NSLog(@"You are the %d%@",i,ordinal);
}

答案 16 :(得分:0)

- (NSString *) formatOrdinalNumber:(NSInteger )number{
    NSString *result = nil;
    //0 remains just 0
    if (number == 0) {
        result = @"0";
    }

    //test for number between 3 and 21 as they follow a
    //slightly different rule and all end with th
    else if (number > 3 && number < 21)
    {
        result = [NSString stringWithFormat:@"%ld th",(long)number];
    }
    else {
        //return the last digit of the number e.g. 102 is 2
        NSInteger lastdigit = number % 10;
        switch (lastdigit)
        {
            case 1: result = [NSString stringWithFormat:@"%ld st",(long)number]; break;
            case 2: result = [NSString stringWithFormat:@"%ld nd",(long)number]; break;
            case 3: result = [NSString stringWithFormat:@"%ld rd",(long)number]; break;
            default: result = [NSString stringWithFormat:@"%ld th",(long)number];
        }
    }
    return result;
}

答案 17 :(得分:0)

这是一个Swift解决方案,循环使用用户的首选语言,直到它找到一个具有已知规则(很容易添加)的序数:

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 "st"
                    }
                default:
                    break
                }
            }
            return ""
        }

        return "\(self)" + ordinalSuffix(self)
    }
}

答案 18 :(得分:0)

您可以尝试一下,简化了。

function numberToOrdinal(n) {

  if (n==0) {
    return n;
   }
   var j = n % 10,
       k = n % 100;


   if (j == 1 && k != 11) {
       return n + "st";
   }
   if (j == 2 && k != 12) {
       return n + "nd";
   }
   if (j == 3 && k != 13) {
       return n + "rd";
   }
   return n + "th";
}

答案 19 :(得分:-4)

这是我的强力实现,以获取日期的NSString *表示并返回序数值。我觉得阅读起来容易得多。

NSDictionary *ordinalDates = @{
    @"1": @"1st",
    @"2": @"2nd",
    @"3": @"3rd",
    @"4": @"4th",
    @"5": @"5th",
    @"6": @"6th",
    @"7": @"7th",
    @"8": @"8th",
    @"9": @"9th",
    @"10": @"10th",
    @"11": @"11th",
    @"12": @"12th",
    @"13": @"13th",
    @"14": @"14th",
    @"15": @"15th",
    @"16": @"16th",
    @"17": @"17th",
    @"18": @"18th",
    @"19": @"19th",
    @"20": @"20th",
    @"21": @"21st",
    @"22": @"22nd",
    @"23": @"23rd",
    @"24": @"24th",
    @"25": @"25th",
    @"26": @"26th",
    @"27": @"27th",
    @"28": @"28th",
    @"29": @"29th",
    @"30": @"30th",
    @"31": @"31st" };