iOS 當請求到的數據是double類型,會失去精准度,並且去掉小數點后的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

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM