ios开发 数字转汉字

+ (NSString *)translationChinese:(NSString *)number

{

    NSString *str = [NSString stringWithFormat:@"%ld",(long)number.integerValue];

    NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];

    NSArray *chinese_numerals = @[@"",@"",@"",@"",@"",@"",@"",@"",@"",@""];

    NSArray *digits = @[@"",@"",@"",@"",@"",@"",@"",@"",@"亿",@"",@"",@"",@""];

    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];

    

    NSMutableArray *sums = [NSMutableArray array];

    for (int i = 0; i < str.length; i ++) {

        NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];

        NSString *a = [dictionary objectForKey:substr];

        NSString *b = digits[str.length -i-1];

        NSString *sum = [a stringByAppendingString:b];

        if ([a isEqualToString:chinese_numerals[9]])

        {

            if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])

            {

                sum = b;

                if ([[sums lastObject] isEqualToString:chinese_numerals[9]])

                {

                    [sums removeLastObject];

                }

            }else

            {

                sum = chinese_numerals[9];

            }

            

            if ([[sums lastObject] isEqualToString:sum])

            {

                continue;

            }

        }

        

        [sums addObject:sum];

    }

    NSString *sumStr = [sums componentsJoinedByString:@""];

    if (str.length == 2) {

        NSComparisonResult result1 = [str compare:@"09"];

        NSComparisonResult result2 = [str compare:@"20"];

        if (result1 == 1 && result2 == -1) {

            sumStr = [sumStr substringFromIndex:1];

        }

    }

    NSString *chinese = [sumStr substringToIndex:sumStr.length-1];

    return chinese;

}

你可能感兴趣的:(iOS开发)