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

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

    You're looking for a combination of "maximum significant digits" and "maximum fraction digits", along with particular rounding behavior. NSNumberFormatter is equal to the task:

    float twofortythreetwentyfive = 234.25;
    float onetwothreefourtwentyfive = 1234.25;
    float eleventwothreefourtwentyfive = 11234.25;
    
    NSNumberFormatter * formatter =  [[NSNumberFormatter alloc] init];
    [formatter setUsesSignificantDigits:YES];
    [formatter setMaximumSignificantDigits:5];
    [formatter setMaximumFractionDigits:2];
    [formatter setRoundingMode:NSNumberFormatterRoundCeiling];
    
    NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:twofortythreetwentyfive]]);
    NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:onetwothreefourtwentyfive]]);
    NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:eleventwothreefourtwentyfive]]);
    

    Result:

    2012-04-26 16:32:04.481 SignificantDigits[11565:707] 234.25
    2012-04-26 16:32:04.482 SignificantDigits[11565:707] 1234.3
    2012-04-26 16:32:04.483 SignificantDigits[11565:707] 11235

提交回复
热议问题