这是字符串操作,而不是数学,因此结果值不会四舍五入:
NSRange range = [price rangeOfString:@"."];
if (range.location != NSNotFound) {
NSInteger index = MIN(range.location+2, price.length-1);
NSString *truncated = [price substringToIndex:index];
}
这主要是字符串操作,欺骗 NSString 为我们做数学:
NSString *roundedPrice = [NSString stringWithFormat:@"%.02f", [price floatValue]];
或者您可能会考虑将所有数值保留为数字,将字符串视为向用户呈现它们的一种方式。为此,请使用 NSNumberFormatter:
NSNumber *priceObject = // keep these sorts values as objects
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *presentMeToUser = [numberFormatter stringFromNumber:priceObject];
// you could also keep price as a float, "boxing" it at the end with:
// [NSNumber numberWithFloat:price];