Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/119.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios NSString对象返回的浮点值不是我期望的值,如何更正从NSString中提取浮点值?_Ios_Objective C_Cocoa Touch_Floating Point_Nsstring - Fatal编程技术网

Ios NSString对象返回的浮点值不是我期望的值,如何更正从NSString中提取浮点值?

Ios NSString对象返回的浮点值不是我期望的值,如何更正从NSString中提取浮点值?,ios,objective-c,cocoa-touch,floating-point,nsstring,Ios,Objective C,Cocoa Touch,Floating Point,Nsstring,在购物车上计算物品的总价格 我有一个存储在核心数据中的字符串£4.44 我使用此代码从字符串中增加数字: + (float)totalPriceOfItems:(NSManagedObjectContext *)managedObjectContext { NSError *error = nil; float totalPrice = 0; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithE

在购物车上计算物品的总价格

我有一个存储在核心数据中的字符串£4.44

我使用此代码从字符串中增加数字:

+ (float)totalPriceOfItems:(NSManagedObjectContext *)managedObjectContext
{
    NSError *error = nil;
    float totalPrice = 0;

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"BagItem"];

    // Get fetched objects and store in NSArray
    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

    for (BagItem *bagItem in fetchedObjects) {
        NSString *price = [[[bagItem price] componentsSeparatedByCharactersInSet:
                            [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                           componentsJoinedByString:@""];
        totalPrice = totalPrice + [price floatValue];

        NSLog(@"total: %f", totalPrice);
    }

    return totalPrice;
}
我要拿回这个值444.000000

当我打算回来的时候4点44分

很明显,我在这里遗漏了一些东西,也许将每件商品的价格存储为一个整数会更好,但现在我想这样做


感谢您抽出时间

问题可能在于您调用的解析代码

[[[bagItem price] componentsSeparatedByCharactersInSet:
                        [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                       componentsJoinedByString:@""]
您要做的是将每个非数字字符上的字符串分开,然后将其重新组合在一起。所以字符串4.44在小数点处被拆分,然后重新组合为444。我的建议是以这样一种方式存储价格,即在需要使用值的地方不需要一些解析代码——您应该将其存储为4.44

现在进入下一个问题-浮动。浮动和双精度在金融应用程序中没有所需的精度。在某个时刻,你将把10.99和0.01相加,发现答案不是11.0,而是11.000000000001或类似的东西。对于这些类型的情况,您应该将数字存储为NSDecimalNumber,并使用类提供的函数进行计算

您可以将字符串转换为NSDecimalNumber,如下所示:

[NSDecimalNumber decimalNumberWithString:@"44.50"];
通过使用NSDecimal数字,您还可以使用us NSNumberFormatter将您的数字格式化为货币(如果您想显示)

[NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterCurrencyStyle];

您应该将
NSNumberFormatter
设置为货币模式来解析字符串。这是可行的,但存在另一个问题。我将发布另一个问题