代码 :
#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;
}
测试它:
- (void)awakeFromNib
{
NSLog(@"%@",[self formatFloat:234.63]);
NSLog(@"%@",[self formatFloat:1234.65]);
NSLog(@"%@",[self formatFloat:11234.65]);
NSLog(@"%@",[self formatFloat:11234]);
}
输出 :
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