字典数值转字符处理

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

strcmp

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

h文件:

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

import <Foundation/Foundation.h>

@interface NSDictionary (hdObjectForKeyAndToString)

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

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

@end
</pre>

m文件:

<pre>
//
// 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

</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 99,757评论 9 468
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,314评论 19 139
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 14,182评论 2 33
  • 北方的雾霾连绵,不可避免地让心情蒙尘。很多人都开始讨厌冬天,因为冬天意味着燃煤、浓烟、大气扩散慢和雾霾。 然而,我...
    平安喜乐岁月静好阅读 2,338评论 1 1
  • 愿你永远年轻 愿你百折不屈 愿你是一只漏网之鱼 ——《愿意吗》 ​​​​
    段童阅读 1,644评论 0 2