Remove More Than 2 Trailing zero

扶醉桌前 提交于 2019-12-17 21:29:05

问题


I have read many question in 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

回答1:


NSNumberFormatter *twoDecimalPlacesFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[twoDecimalPlacesFormatter setMaximumFractionDigits:2];
[twoDecimalPlacesFormatter setMinimumFractionDigits:0];

return [twoDecimalPlacesFormatter stringFromNumber:number];



回答2:


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



回答3:


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];


来源:https://stackoverflow.com/questions/7469614/remove-more-than-2-trailing-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!