如何在找到某个字符后截断NSString'x'字符

时间:2013-10-02 03:20:41

标签: ios objective-c nsstring truncate

假设我有一个NSString,它代表的价格当然是双倍的。我试图让它在百分之一的地方截断字符串,所以它就像19.99而不是19.99412092414。有没有办法,一旦检测到十进制就像这样......

if ([price rangeOfString:@"."].location != NSNotFound)
    {
        // Decimal point exists, truncate string at the hundredths.
    }

让我在“。”之后切断字符串2个字符,而不将其分成数组,然后在decimal上执行最大尺寸截断,最后重新组装它们?

非常感谢您提前! :)

1 个答案:

答案 0 :(得分: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];