美文网首页
字典数值转字符处理

字典数值转字符处理

作者: 吾乃常山赵子龙 | 来源:发表于2017-07-19 20:12 被阅读0次

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

    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>

    相关文章

      网友评论

          本文标题:字典数值转字符处理

          本文链接:https://www.haomeiwen.com/subject/hykrkxtx.html