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

后端 未结 4 814
一整个雨季
一整个雨季 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:37

    Here is how I implemented this in my code. I don't know how efficient it is, I hope not bad.

    So I create a global NSNumberFormatter

    NSNumberFormatter* numFormatter; 
    

    and initialize it somewhere:

    numFormatter=[[NSNumberFormatter alloc]init];
    

    Then I format number with the following function:

    - (NSString*)formatFloat:(Float32)number withOptimalDigits:(UInt8)optimalDigits maxDecimals:(UInt8)maxDecimals
    {
        NSString* result;
        UInt8 intDigits=(int)log10f(number)+1;
        NSLog(@"Formatting %.5f with maxDig: %d maxDec: %d intLength: %d",number,optimalDigits,maxDecimals,intDigits);  
    
        numFormatter.maximumFractionDigits=maxDecimals;
        if(intDigits>=optimalDigitis-maxDecimals) {
            numFormatter.usesSignificantDigits=YES;
            numFormatter.maximumSignificantDigits=(intDigits>optimalDigits)?intDigits:optimalDigits;
        } else {
            numFormatter.usesSignificantDigits=NO;
        }
        result = [numFormatter stringFromNumber:[NSNumber numberWithFloat:number]];
    
        return result;
    }
    

提交回复
热议问题