2

假设我有一个NSString,它代表的价格当然是双倍的。我试图让它在百分之一处截断字符串,所以它类似于19.99而不是19.99412092414例如。有没有办法,一旦像这样检测到小数......

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

让我在“。”之后切断字符串 2 个字符,而不将它分成一个数组,然后decimal在最后重新组装它们之前对它们进行最大大小截断?

非常感谢您!:)

4

1 回答 1

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];
于 2013-10-02T03:38:22.810 回答