2

私が を持っているNSStringとしましょう。それは価格を表し、それ以外の場合はもちろん 2 倍になります。文字列を 100 分の 1 で切り捨てようとしているので、たとえばでは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 に答える