【问题标题】:How to truncate an NSString 'x' characters after a certain character is found找到某个字符后如何截断 NSString 'x' 字符
【发布时间】:2013-10-08 09:33:12
【问题描述】:
假设我有一个NSString,它代表的价格当然会翻倍。我试图让它在百分之一处截断字符串,所以它类似于19.99,而不是19.99412092414。有没有办法,一旦像这样检测到小数...
if ([price rangeOfString:@"."].location != NSNotFound)
{
// Decimal point exists, truncate string at the hundredths.
}
让我在 "." 之后切断字符串 2 个字符,而不是将其分成一个数组,然后在最后重新组装它们之前对 decimal 进行最大大小截断?
提前非常感谢您! :)
【问题讨论】:
标签:
ios
objective-c
nsstring
truncate
【解决方案1】:
这是字符串操作,而不是数学运算,因此结果值不会被四舍五入:
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];