Ios 如何截断NSString';x';找到某个字符后的字符

Ios 如何截断NSString';x';找到某个字符后的字符,ios,objective-c,nsstring,truncate,Ios,Objective C,Nsstring,Truncate,假设我有一个NSString,它表示的价格当然是双倍的。我试图让它在第一百位截断字符串,因此它类似于19.99,而不是19.99412092414。有没有一种方法,一旦像这样检测到小数点 if ([price rangeOfString:@"."].location != NSNotFound) { // Decimal point exists, truncate string at the hundredths. } 对于我来说,在“.”之后切掉字符串2个字

假设我有一个
NSString
,它表示的价格当然是双倍的。我试图让它在第一百位截断字符串,因此它类似于
19.99
,而不是
19.99412092414
。有没有一种方法,一旦像这样检测到小数点

if ([price rangeOfString:@"."].location != NSNotFound)
    {
        // Decimal point exists, truncate string at the hundredths.
    }
对于我来说,在“.”之后切掉字符串2个字符,而不将其拆分为数组,然后在最后重新组合它们之前对
十进制进行最大大小的截断


提前非常感谢!:)

这是字符串操作,而不是数学,因此结果值不会四舍五入:

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