Limiting both the fractional and total number of digits when formatting a float for display

后端 未结 4 815
一整个雨季
一整个雨季 2021-01-17 22:09

I need to print a float value in area of limited width most efficiently. I\'m using an NSNumberFormatter, and I set two numbers after the decimal point as the d

4条回答
  •  感情败类
    2021-01-17 22:34

    Code :

    #define INTPARTSTR(X) [NSString stringWithFormat:@"%d",(int)X]
    #define DECPARTSTR(X) [NSString stringWithFormat:@"%d",(int)(((float)X-(int)X)*100)]
    
    - (NSString*)formatFloat:(float)f
    {
        NSString* result;
    
        result = [NSString stringWithFormat:@"%.2f",f];
    
        if ([DECPARTSTR(f) isEqualToString:@"0"]) return INTPARTSTR(f);
        if ([INTPARTSTR(f) length]==5) return INTPARTSTR(f);
    
        if ([result length]>5)
        {
            int diff = (int)[result length]-7;
    
            NSString* newResult = @"";
    
            for (int i=0; i<[result length]-diff-1; i++)
                newResult = [newResult stringByAppendingFormat:@"%c",[result characterAtIndex:i]];
    
            return newResult;
        }
    
    
        return result;
    }
    

    Testing it :

    - (void)awakeFromNib
    {
        NSLog(@"%@",[self formatFloat:234.63]);
        NSLog(@"%@",[self formatFloat:1234.65]);
        NSLog(@"%@",[self formatFloat:11234.65]);
        NSLog(@"%@",[self formatFloat:11234]);
    }
    

    Output :

    2012-04-26 19:27:24.429 newProj[1798:903] 234.63
    2012-04-26 19:27:24.432 newProj[1798:903] 1234.6
    2012-04-26 19:27:24.432 newProj[1798:903] 11234
    2012-04-26 19:27:24.432 newProj[1798:903] 11234
    

提交回复
热议问题