Remove More Than 2 Trailing zero
I have read many question in开发者_JAVA百科 stack overflow, what I want is remove 2 or more than two trailing zero behind the decimal. i.e:
12.00 ==> 12
12.30 ==> 12.30
12.35 ==> 12.35
12.345678 ==> 12.34
NSNumberFormatter *twoDecimalPlacesFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[twoDecimalPlacesFormatter setMaximumFractionDigits:2];
[twoDecimalPlacesFormatter setMinimumFractionDigits:0];
return [twoDecimalPlacesFormatter stringFromNumber:number];
I like @dorada's answer, here is a complete test:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:0];
NSLog(@"12.00 ==> %@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.00]]);
NSLog(@"12.30 ==> %@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.30]]);
NSLog(@"12.35 ==> %@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.35]]);
NSLog(@"12.345678 ==> %@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345678]]);
NSLog output:
12.00 ==> 12
12.30 ==> 12.3
12.35 ==> 12.35
12.345678 ==> 12.35
Try:
NSLog(@"%0.2f", 12.345678);
Or to save it to an NSString:
NSString *numberString = [NSString stringWithFormat:@"%0.2f", 12.345678];
Edit
Missed the fact that you didn't want any zero fraction digits. Credits to @dorada for this one:
NSNumber *number = [NSNumber numberWithFloat:12.00];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:0];
NSString *numberString = [formatter stringFromNumber:number];
[formatter release];
精彩评论