How get the total sum of currency from a NSMutableArray [duplicate] - ios

This question already has answers here:
ios - How get the total sum of float from a NSMutableArray
(3 answers)
Closed 8 years ago.
I want to sum of currency from NSMutableArray. Ex: I have an arrayA (1,234.56 , 2,345.67) and after sum items in array, I want result show: 3,580.23 to put it on the Label. Is there the way to implement this?
Thanks

If the values are stored as NSNumber objects, you can use the collection operators. For example:
NSArray *array = #[#1234.56, #2345.67];
NSNumber *sum = [array valueForKeyPath:#"#sum.self"];
If you want to format that sum nicely using NSNumberFormatter:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *result = [formatter stringFromNumber:sum];
NSLog(#"result = %#", result);
If your values are really represented by strings, #"1,234.56", #"2,345.67", etc., then you might want to manually iterate through the array, converting them to numeric values using the NSNumberFormatter, adding them up as you go along:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSArray *array = #[#"1,234.56", #"2,345.67"];
double sum = 0.0;
for (NSString *string in array) {
sum += [[formatter numberFromString:string] doubleValue];
}
NSString *result = [formatter stringFromNumber:#(sum)];
NSLog(#"result = %#", result);

The simplest way is this:
NSMutableArray *array = [NSMutableArray arrayWithArray:#[#(1234.56), #(2345.67)]];
double sum = [[array valueForKeyPath: #"#sum.self"] doubleValue];

Related

is there any way to add integers from an array without take elements to outside [duplicate]

This question already has answers here:
ios - How get the total sum of float from a NSMutableArray
(3 answers)
Closed 8 years ago.
I want to sum of currency from NSMutableArray. Ex: I have an arrayA (1,234.56 , 2,345.67) and after sum items in array, I want result show: 3,580.23 to put it on the Label. Is there the way to implement this?
Thanks
If the values are stored as NSNumber objects, you can use the collection operators. For example:
NSArray *array = #[#1234.56, #2345.67];
NSNumber *sum = [array valueForKeyPath:#"#sum.self"];
If you want to format that sum nicely using NSNumberFormatter:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *result = [formatter stringFromNumber:sum];
NSLog(#"result = %#", result);
If your values are really represented by strings, #"1,234.56", #"2,345.67", etc., then you might want to manually iterate through the array, converting them to numeric values using the NSNumberFormatter, adding them up as you go along:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSArray *array = #[#"1,234.56", #"2,345.67"];
double sum = 0.0;
for (NSString *string in array) {
sum += [[formatter numberFromString:string] doubleValue];
}
NSString *result = [formatter stringFromNumber:#(sum)];
NSLog(#"result = %#", result);
The simplest way is this:
NSMutableArray *array = [NSMutableArray arrayWithArray:#[#(1234.56), #(2345.67)]];
double sum = [[array valueForKeyPath: #"#sum.self"] doubleValue];

NSNumber numberFromString not placed decimals

I am trying to convert NSString to NSNumber and it seems to create a decimal point issue here.
NSString *str = #"515.51515";
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:str];
NSLog(#"Number here:%#",myNumber);
[f release];
& result print is
2015-03-01 08:09:28.353 myApp [57376:2086924] Number here: 515.5151499999999
Actual debug log picture here
but actually it should be 515.51515 rather 515.5151499999999.
I tried all comibination with f.usesSignificantDigits & f.maximumFractionDigits =10 but no luck.
please let me know How to fix this?
RMaddy is correct, floating point numbers will be a bit off.
Since an NSDecimalNumber is an NSNumber you can use:
NSNumber *number = [NSDecimalNumber decimalNumberWithString:#"515.51515"];
Try to use construction:
NSNumber *myNumber = [NSNumber numberWithFloat:[str floatValue]];
I think it should work correctly.

Get maximum value from NSMutableArray [duplicate]

This question already has answers here:
Getting Max Date from NSArray, KVC
(2 answers)
Closed 8 years ago.
How can I get a maximum value from an NSMutableArray. Values are stores as NSString in array as below
for(int counter=0; counter<[datesArray count];counter++)
{
glass = [NSString stringWithFormat:#"%f",[[dbhandler todayData:currentDate] floatValue]];
[graphGlassesArray addObject:glass];
}
Array name is graphGlassesArray.
You can get the max value from an array using:
NSNumber* max = [graphGlassesArray valueForKeyPath:#"max.self"];
float maxFloat = [max floatValue]
You should also try to use Key Value Coding (https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html). To obrain the max in a NSArray you can do [array valueForKeyPath:#"#max.attribute"]. Try to look at this link http://nshipster.com/kvc-collection-operators/.
float max = 0.f;
for(int counter=0; counter<[datesArray count];counter++)
{
glass = [NSString stringWithFormat:#"%f",[[dbhandler todayData:currentDate] floatValue]];
[graphGlassesArray addObject:glass];
if(max < [[dbhandler todayData:currentDate] floatValue]) {
max = [[dbhandler todayData:currentDate] floatValue];
}
}
Try with this
Try by sorting the mutable array
NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:nil ascending:NO selector:#selector(localizedCompare:)];
NSString *maxValue = [[graphGlassesArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]] objectAtIndex:0];
[desc release];

How to get the data from a row in an NSArray using only part of the row to search

Lets say i have an array filled with several rows
dates = [NSArray arrayWithObjects:#"2012-05-01||Blue", #"2012-05-02||Red", #"2012-05-03||Green", #"2012-05-04||Orange", #"2012-05-05||Yellow", #"2012-05-06||Purple", #"2012-05-07||Silver", nil];
and then I have a date to search by 2012-05-01
How do i search for an object by only part of it without doing a big for( loop because this array will theoretically hold a few thousand cells.
EDIT:
if necessary how do i load the data into an NSDictionary? (i've never used them)
I know i can get the data like so
for(NSString *row in dates) {
NSString *date = [[row componentsSeperatedByString:#"||"] objectAtIndex:0];
NSString *color = [[row componentsSeperatedByString:#"||"] objectAtIndex:1];
}
NSMutableDictionary *colorsAndDates = [[NSMutableDictionary alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
for(NSString *row in dates) {
NSString *dateString = [[row componentsSeparatedByString:#"||"] objectAtIndex:0];
NSDate *date = [dateFormatter dateFromString:dateString];
NSString *color = [[row componentsSeparatedByString:#"||"] objectAtIndex:1];
[colorsAndDates setObject:color forKey:date];
}
If I am correct, this will format it into an NSDictionary, and then I can grab the color using:
NSString *dateToFind = #"2012-05-01";
NSDate *date = [dateFormatter dateFromString:dateToFind];
NSString *theColor = [colorsAndDates objectForKey:date];
Knowing this, I will have to go back and make it all revolve around NSDictionary instead of the strings they're in.
There's a couple of things you can do other than looping through the array:
1) Use a sorted array. Even if you need to keep the data in the initial order, you can make a sorted copy of it. Then you can do a binary search (if there are n items, check the n/2 item, if it's less than your date and repeat the process with only the data from n/2 to n, or if it's greater, then repeat with the data from 0 to n/2. Sort once, find many.
2) Create a dictionary on the fly using the data. You can use the the 10 character prefix of the data as the key. You'll have to maintain the dictionary along with the array, so this may not be practicable if you have a lot of changes. Create dictionary once, find many. (Note: despite the answers you've gotten, a dictionary may not be the best solution, particularly if you don't have unique keys (i.e. more than one record with the same date).
3) Forget the arrays and store your data in sqlite, and write a sql statement to get it. Most useful if you have a whole lot of data. You can use sqlite to build a primary key if you have duplicate dates in your data.
Creating a dictionary:
NSDictionary *dateDictionary = #{
#"2012-05-01" : #"Blue",
#"2012-05-02" : #"Red",
#"2012-05-03" : #"Green",
#"2012-05-04" : #"Orange",
#"2012-05-05" : #"Yellow",
#"2012-05-06" : #"Purple",
#"2012-05-07" : #"Silver"
};
NSString *date = #"2012-05-01";
NSString *dateColor = dateDictionary[date];
Using the example you gave (looping through the array to create a dictionary):
NSMutableDictionary *dateDictionary = [NSMutableDictionary dictionary];
for(NSString *row in dates) {
NSString *date = [[row componentsSeperatedByString:#"||"] objectAtIndex:0];
NSString *color = [[row componentsSeperatedByString:#"||"] objectAtIndex:1];
dateDictionary[date] = color;
}
NSString *date = #"2012-05-01";
NSString *dateColor = dateDictionary[date];

How to convert elements of NSMutableArray (NString) to NSNumber and add them up?

Ok so I have NsMutable array with Strings which are in format:
32,45,54,5550 etc.
What is the easiest way to convert all these strings to nsnumber and also get the sum of entire array.
You can use the KVC collection operator #sum to get the summation of all number strings stored in an array
NSArray *numberStrings = #[#"32",#"45",#"54",#"5550"];
NSNumber* sum = [numberStrings valueForKeyPath: #"#sum.self"];
NSLog(#"%#", sum);
output: 5681
For simple strings it works. But caution: in localization there might be traps. There-for I would still suggest to use a NSNumberFormatter to create real NSNumber objects, store them in another array and use #sum on that.
Thanks Bryan Chen for make me test.
To raise the awareness for problems that might lie in localization, I want to share this experiment with you:
In German we use , to separate the decimal digits, where as we use the . to group long numbers in thousands.
So if the numberString array might be filled with german formatted numbers, it might look like #[#"32,5", #"45", #"54", #"5.550,00"]. The sum of this is 5681.5, but if we do not alter the code, it will not fail, but worse — miscalculate: 136.55. It just ignored everything past a comma and treated . as decimal separator.
Lets use a NSNumberFormatter to fix it:
My system is set to german locale
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
nf.locale = [NSLocale currentLocale];
[nf setGroupingSize:3];
nf.usesGroupingSeparator= YES;
NSArray *numberStrings = #[#"32,5", #"45", #"54", #"5.550,00"];
NSMutableArray *numbers = [#[] mutableCopy];
for (NSString *s in numberStrings) {
NSNumber *n = [nf numberFromString:s];
[numbers addObject:n];
}
NSNumber* sum = [numbers valueForKeyPath: #"#sum.self"];
NSLog(#"%#", sum);
it prints correctly 5681.5.
NSArray *array = #[ #"1,2", #"3,4" ];
NSUInteger sum = 0;
for (NSString *str in array)
{
for (NSString *num in [str componentsSeparatedByString:#","])
{
sum += [num intValue];
}
}
or
NSArray *array = #[ #"1", #"3" ];
NSUInteger sum = 0;
for (NSString *num in array)
{
sum += [num intValue];
}

Resources