【OBJC】數字轉中文大寫

博客園都不知道怎麼外鏈圖片……app

 

- (void)numToString:(double)num{
    int iLen,iNum,iAddZero=0;
    NSMutableString *szChMoney = [[NSMutableString alloc] init];
    NSArray *hzUnit = @[@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@""];
    NSArray *hzNum = @[@"",@"",@"",@"",@"",@"",@"",@"",@"",@""];
    
    NSString *szNum = [NSString stringWithFormat:@"%18.0f",num*100];
    szNum = [szNum stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    iLen = szNum.length;
    
    if ((iLen > 18) || (iLen == 0) || num == 0) {
        return;
    }
    for (int i = 0; i < iLen; i++) {
        iNum = [[szNum substringWithRange:NSMakeRange(i, 1)] intValue];
        if (iNum == 0) {
            iAddZero++;
        }
        else {
            if (iAddZero > 0) {
                [szChMoney appendString:@""];
            }
            [szChMoney appendString:hzNum[iNum]];
            iAddZero = 0;
        }
        if (iNum != 0                                       //數字不等於0 添加單位
            || iLen - i == 3                                //處理個位單位
            || iLen - i == 11                               //處理億位單位
            || ((iLen - i + 1) % 8 == 0 && iAddZero < 4))   //處理萬位單位
        {
            [szChMoney appendString:hzUnit[iLen-i-1]];
        }
    }
    if ([[szNum substringWithRange:NSMakeRange(iLen-2, 2)] isEqualToString:@"00"]) {
        [szChMoney appendString:@""];
    }
    NSLog(@"%@",szChMoney);
}
相關文章
相關標籤/搜索