objective-c - 从 NSDictionary 对象中计算货币

标签 objective-c ios nsnumberformatter nsenumerator

基本思想是迭代一个充满 .plist 的目录,其中包含包含货币值的 NSDictionary 对象。

问题

如何迭代所有目录内容并提取所有“当前值”对象并将它们加在一起以获得总金额?

示例

NSArray * itemList = [MANAGER contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@",INVENTORY_PATH] error:nil];
for ( NSString * item in itemList )
{
    NSDictionary * currentItem = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",INVENTORY_PATH, item]];

    float monetaries = [[currentItem objectForKey:@"Current Value"] floatValue];

    NSLog(@"Current Value: %.2f",monetaries);       
} 

当前输出

2012-05-06 22:11:33.583 WrightsCS[3151:15803] Current Value: 350.99
2012-05-06 22:11:33.584 WrightsCS[3151:15803] Current Value: 321.54

期望的输出

2012-05-06 22:11:33.584 WrightsCS[3151:15803] Total Value: 672.53

解决方案

float total = 0.0f ;
float monetaries = 0.0f;

NSArray * itemList = [MANAGER contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@",INVENTORY_PATH] error:nil];
for ( NSString * item in itemList )
{
    NSDictionary * currentItem = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",INVENTORY_PATH, item]];

    monetaries = [[currentItem objectForKey:@"Current Value"] floatValue];
    total += monetaries ;     

    NSLog(@"Current Value: %.2f",monetaries);  
}    

NSLog(@"Total Value: %.2f",total);  

解决方案输出

2012-05-06 22:26:05.460 WrightsCS[3205:15803] Current Value: 350.99
2012-05-06 22:26:05.462 WrightsCS[3205:15803] Current Value: 321.54
2012-05-06 22:26:05.462 WrightsCS[3205:15803] Total Value: 672.53

最佳答案

你不能只保留一个运行总数还是我错过了?

NSArray * itemList = [MANAGER contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@",INVENTORY_PATH] error:nil];

float total = 0.0f ;
for ( NSString * item in itemList )
{
    NSDictionary * currentItem = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",INVENTORY_PATH, item]];

    float monetaries = [[currentItem objectForKey:@"Current Value"] floatValue];
    total += monetaries ;
//    NSLog(@"Current Value: %.2f",monetaries);       
} 

NSLog(@"Total Value: %.2f",monetaries);       

关于objective-c - 从 NSDictionary 对象中计算货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10476285/

相关文章:

objective-c - UIWebView 发布导致崩溃

ios - TTTAttributedLabel "Read More >"尾部截断可能有几个属性?

ios - AES 128 与 CBC

swift3 - 如何使用 NumberFormatter() 在 swift 3 中设置 maximumFractionDigits

cocoa - NSNumberFormatter 通过 StoryBoard - Xcode 9

ios - 如何在 Mac/iOS 上获取当前语言环境的负号字符

objective-c - 将字符串中出现的两个字符相互替换

iphone - 以编程方式访问应用标识符前缀

ios - iTunes Connect 不显示 "App Store Status"下的任何内容

ios - NSPointerFunctionsCopy 困惑