字典数值转字符处理

后台返回的数字格式在前端转字符展示时出现误差,所以自己写了下面这些。

strcmp


C/C++函数,比较两个字符串
设这两个字符串为str1,str2,
若str1==str2,则返回零;用到了这个,嘿嘿。
若str1 若str1>str2,则返回正数。

h文件:


//
// NSDictionary+hdObjectForKeyAndToString.h
// JC
//
// Created by CML on 2017/7/19.
// Copyright © 2017年 zhaozilong. All rights reserved.
//

import

@interface NSDictionary (hdObjectForKeyAndToString)

/**
根据不同的数据类型取NSNumber的值.

@param key keyString
@return resultString
/
-(NSString
)hdObjectForKeyAndToString:(NSString*)key;

@end

m文件:


//
// NSDictionary+hdObjectForKeyAndToString.m
// JC
//
// Created by CML on 2017/7/19.
// Copyright © 2017年 zhaozilong. All rights reserved.
//

import "NSDictionary+hdObjectForKeyAndToString.h"

@implementation NSDictionary (hdObjectForKeyAndToString)

-(NSString)hdObjectForKeyAndToString:(NSString)key{
id result=[self objectForKey:key];
if([result isKindOfClass:[NSNumber class]]){
return [self hdNumberString:result];
}
return [result description];
}

-(NSString)hdNumberString:(NSNumber)number{
NSString *result=@"";
const char *type=[number objCType];
if (strcmp (type, @encode (NSInteger)) == 0) {
result=[NSString stringWithFormat:@"%ld",[number integerValue]];
} else if (strcmp (type, @encode (NSUInteger)) == 0) {
result=[NSString stringWithFormat:@"%lu",[number unsignedIntegerValue]];
} else if (strcmp (type, @encode (int)) == 0) {
result=[NSString stringWithFormat:@"%d",[number intValue]];
} else if (strcmp (type, @encode (float)) == 0) {
result=[NSString stringWithFormat:@"%f",[number floatValue]];
} else if (strcmp (type, @encode (double)) == 0) {
result=[NSString stringWithFormat:@"%lf",[number doubleValue]];
} else if (strcmp (type, @encode (long)) == 0) {
result=[NSString stringWithFormat:@"%ld",[number longValue]];
} else if (strcmp (type, @encode (long long)) == 0) {
result=[NSString stringWithFormat:@"%lld",[number longLongValue]];
} else {
result=[NSString stringWithFormat:@"%ld",[number integerValue]];
}
if ([[result componentsSeparatedByString:@"."] count]>1) {
result=[result stringByReplacingOccurrencesOfString:@"0+$"
withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [result length])];
}
return result;
}

@end

你可能感兴趣的:(字典数值转字符处理)