2012-01-07 74 views

回答

7

一個最簡單的解決辦法是使用stringWithFormat:NSString的:

NSString* result = [NSString stringWithFormat: @"%5.2f", floatVal]; 
0

試試這個..

-(NSString*)floatToString:(float)val 
{ 

    NSString *result; 
    NSArray *numbers = [[NSArray alloc]initWithObjects:[NSString stringWithFormat:@"%f",val], nil]; 
    NSLog(@"%@",numbers); 


    NSArray * floatingPoint = [[numbers objectAtIndex:0] componentsSeparatedByString:@"."]; 
    NSString * lastObject = [[floatingPoint lastObject] stringByReplacingOccurrencesOfString:@"0" withString:@""]; 

     if ([lastObject length] < 2) { 
      result = [NSString stringWithFormat:@"$ %.2f",[[numbers objectAtIndex:0] floatValue]]; 
     } else { 
      result = [NSString stringWithFormat:@"$ %g",[[numbers objectAtIndex:0] floatValue]]; 
     } 

    return result; 
}