首页 > 移动平台 > 详细

iOS 当请求到的数据是double类型,会失去精准度,并且去掉小数点后的0

时间:2016-12-20 17:57:41      阅读:632      评论:0      收藏:0      [点我收藏+]

首先请求到的数据都会变成字符串,先将字符串转化为double类型

double fdouble = [str doubleValue];

然后再设置小数点后的位数

[NSString stringWithFormat:@"%.1f", fdouble];

 重点:  提供一个NSSing的扩展,传入需要保留的小数位,返回字符串。并且去掉末尾的0.

#import <Foundation/Foundation.h>

@interface NSString (EliminateZero)

//   integer  必传
- (NSString *)eliminateZeroWithDouble:(NSInteger)integer;

@end



#import "NSString+EliminateZero.h"

@implementation NSString (EliminateZero)

- (NSString *)eliminateZeroWithDouble:(NSInteger)integer{
    
    NSString *str = [self copy];
    
    double fdouble = [str doubleValue];
    
    NSString *ftotal;
    switch (integer) {
        case 1:
            ftotal = [NSString stringWithFormat:@"%.1f", fdouble];
            break;
        case 2:
            ftotal = [NSString stringWithFormat:@"%.2f", fdouble];
            break;
        case 3:
            ftotal = [NSString stringWithFormat:@"%.3f", fdouble];
            break;
        case 4:
            ftotal = [NSString stringWithFormat:@"%.4f", fdouble];
            break;
        case 5:
            ftotal = [NSString stringWithFormat:@"%.5f", fdouble];
            break;
        default:
            break;
    }

    while ([ftotal hasSuffix:@"0"]) {
        ftotal = [ftotal substringToIndex:[ftotal length]-1];
    }
    
    if ([ftotal hasSuffix:@"."]) {
        ftotal = [ftotal substringToIndex:[ftotal length]-1];
    }
    
    return ftotal;
    
}


@end

 

 

 

 

iOS 当请求到的数据是double类型,会失去精准度,并且去掉小数点后的0

原文:http://www.cnblogs.com/weipeng168/p/6203531.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!