我已经在堆栈溢出中读了很多问题,我想要的是删除小数后面的2个或两个以上的尾随零。即:
12.00 ==> 12
12.30 ==> 12.30
12.35 ==> 12.35
12.345678 ==> 12.34
答案 0 :(得分:9)
NSNumberFormatter *twoDecimalPlacesFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[twoDecimalPlacesFormatter setMaximumFractionDigits:2];
[twoDecimalPlacesFormatter setMinimumFractionDigits:0];
return [twoDecimalPlacesFormatter stringFromNumber:number];
答案 1 :(得分:3)
我喜欢@ dorada的回答,这是一个完整的测试:
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输出:
12.00 ==> 12
12.30 ==> 12.3
12.35 ==> 12.35
12.345678 ==> 12.35
答案 2 :(得分:0)
尝试:
NSLog(@"%0.2f", 12.345678);
或者将其保存到NSString:
NSString *numberString = [NSString stringWithFormat:@"%0.2f", 12.345678];
修改强>
错过了您不想要任何零分数的事实。 @dorada对此项的致谢:
NSNumber *number = [NSNumber numberWithFloat:12.00];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:0];
NSString *numberString = [formatter stringFromNumber:number];
[formatter release];