38

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の回答から適応 .NETで数字の「st」、「nd」、「rd」、「th」の末尾を取得する簡単な方法はありますか?

4

20 に答える 20

43

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
于 2016-05-08T23:54:38.370 に答える
22

これは1つの方法(英語の場合)でトリックを行います。PHPの元のコードを提供してくれたnickfhttps : //stackoverflow.com/a/69284/1208690に感謝します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;
}
于 2012-04-20T17:41:45.467 に答える
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 オブジェクトとしてインスタンス化し、テキスト フィールドのフォーマッタ アウトレットをそれにアタッチします。より細かい制御 (最大値と最小値の設定など) を行うには、フォーマッタのインスタンスを作成し、必要に応じてプロパティを設定し、そのメソッドを使用してテキスト フィールドにアタッチする必要がありますsetFormatter:

クラスは GitHub からダウンロードできます(サンプル プロジェクトを含む)。

于 2010-07-23T07:09:47.900 に答える
14

-- スイフト 4/5 --

     let num = 1
     let formatter = NumberFormatter()
     formatter.numberStyle = .ordinal
     let day = formatter.string(from: NSNumber(value: num))
     
     print(day!)
     result - 1st
于 2017-12-29T10:11:57.517 に答える
7

英語ではとても簡単です。迅速な拡張機能は次のとおりです。

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
于 2014-11-14T06:17:20.733 に答える
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日

于 2016-03-15T19:46:16.930 に答える
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;
}
于 2012-06-07T00:39:19.150 に答える
3

私はこの能力を認識していません。ただし、これを自分で行うことは可能です。英語では、序数 (th、st、nd、rd など) は非常に単純なパターンを持っています。

番号が次で終わる場合: => 使用:

  • 0 => 番目
  • 1 => st
  • 2 => nd
  • 3 => 番目
  • 4 => 番目
  • 5 => 番目
  • 6 => 番目
  • 7 => 番目
  • 8 => 番目
  • 9 => 番目
  • 11 => 番目
  • 12 => 番目
  • 13 => 番目

これはあなたのために単語を綴りませんが、「42nd」、「1,340,697th」などのようなことをすることができます.

ローカライズが必要な場合、これはさらに複雑になります。

于 2010-07-22T20:11:21.737 に答える
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"
        }
    }

}
于 2016-02-21T20:41:51.163 に答える
2

次の例は、任意の数値を処理する方法を示しています。これは c# ですが、任意の言語に簡単に変換できます。

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

于 2010-07-22T20:41:43.587 に答える
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);
}
于 2015-08-19T21:24:18.433 に答える
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
    }
}
于 2016-09-13T19:12:39.113 に答える
-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" };
于 2014-02-03T15:51:29.697 に答える