willbattel
willbattel

Reputation: 1120

How to truncate an NSString 'x' characters after a certain character is found

Say I have an NSString, it represents a price that otherwise would be a double of course. I am trying to make it truncate the string at the hundredths place so it is something like 19.99 instead of 19.99412092414 for example. Is there a way, once detecting the decimal like so...

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

for me to cut off the string 2 characters after that ".", without separating it into an array then doing a max size truncate on the decimal before finally reassembling them?

Thank you very much in advance! :)

Upvotes: 2

Views: 1029

Answers (1)

danh
danh

Reputation: 62676

This is string manipulation, not math, so the resulting value won't be rounded:

NSRange range = [price rangeOfString:@"."];
if (range.location != NSNotFound) {
    NSInteger index = MIN(range.location+2, price.length-1);
    NSString *truncated = [price substringToIndex:index];
}

This is mostly string manipulation, tricking NSString into doing that math for us:

NSString *roundedPrice = [NSString stringWithFormat:@"%.02f", [price floatValue]];

Or you might consider keeping all numeric values as numbers, thinking of strings as just a way to present them to the user. For that, use 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];

Upvotes: 2

Related Questions