How to sum two elements of the array? - objective-c

NSMutableArray *array = [NSMutableArray arrayWithObjects:#"22,343", #"44,323",#"34,5678",#"22,725", nil];
i have this array and I want to sum two values this array.
like this array[0] + array [1]
how to sum this elements?
thanks !!

Solution is
NSString *strVaue1 = [array[0] stringByReplacingOccurrencesOfString:#"," withString:#""];
NSString *strVaue2 = [array[1] stringByReplacingOccurrencesOfString:#"," withString:#""];
NSUInteger arrValue1 = [strVaue1 integerValue];
NSUInteger arrValue2 = [strVaue2 integerValue];
NSUInteger sum = arrValue1 + arrValue2;
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setNumberStyle:NSNumberFormatterDecimalStyle]; // to get commas (or locale equivalent)
[fmt setMaximumFractionDigits:0]; // to avoid any decimal
NSString *result = [fmt stringFromNumber:#(sum)];
NSLog(#"The result is - %#",result);
The printed result is
The result is - 66,666

Related

Objective C remove trailing zeros after decimal place

I am trying to get number in 2 decimal places with trailing zeros.
e.g
11.633-> 11.63
11.630-> 11.63
11.60-> 11.6
11-> 11
12928.98-> 12928.98
for this I written below line
#define kFloatFormat2(x) [NSString stringWithFormat:#"%g", [[NSString stringWithFormat:#"%.2f", x] floatValue]]
NSNumber *number1 = [NSNumber numberWithDouble:12928.98];
NSLog(#"number1:%#", number1);
NSString *string1 = kFloatFormat2([number1 floatValue]);
NSLog(#"string1:%#", string1);
the output of above prints
number1:12928.98
string1:12929
Why it prints 12929 value for string1
I want it as 12928.98.
Have you tried using a number formatter?
NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesGroupingSeparator:NO];
[formatter setMaximumFractionDigits:fractionDigits];
[formatter setMinimumFractionDigits:fractionDigits];
Now do something like
NSNumber *x = #23423;
NSString *value = [formatter stringFromNumber:x];
NSLog(#"number = %#, value);
You macro makes no sense. Just make it:
#define kFloatFormat2(x) [NSString stringWithFormat:#"%.2f", [x floatValue]]
where x is an NSNumber. And then you would call it like this:
NSString *string1 = kFloatFormat2(number1);
Or just do this:
double x = 12928.98;
NSLog(#"number = %.2f", x);

NSNumberFormatter to stop shortening numbers

EDIT: Fixed, here is how i did it for furture reference:
NSNumber *inputNumber = [[NSNumber alloc ]initWithDouble:convertValue];
NSNumber *resultNumber = [[NSNumber alloc]initWithDouble:result];
NSNumberFormatter *formatterResult = [[NSNumberFormatter alloc] init];
formatterResult.numberStyle = NSNumberFormatterDecimalStyle;
NSNumberFormatter *formatterInput = [[NSNumberFormatter alloc] init];
formatterInput.numberStyle = NSNumberFormatterDecimalStyle;
[formatterResult setNumberStyle:NSNumberFormatterDecimalStyle];
[formatterResult setMaximumFractionDigits:6];
[formatterInput setNumberStyle:NSNumberFormatterDecimalStyle];
[formatterInput setMaximumFractionDigits:6];
//These four lines are the one fixing the issue.
NSString *formattedResultString = [formatterResult stringFromNumber:(NSNumber*)resultNumber];
NSString *formattedInputString = [formatterInput stringFromNumber:(NSNumber*)inputNumber];
NSString *formelString = [[NSString alloc]initWithFormat:
#" %# %# =", formattedInputString, convertFromName];
formelLabel.text = formelString;
NSString *resultString = [[NSString alloc]initWithFormat:
#" %# %#",formattedResultString, convertToName];
resultLabel.text = resultString;
----------ORIGINAL QUESTION------------
So I have a problem with NSNumberFormatter shortening numbers too much, and also not displaying decimals when the main number is over 8 digits.
Problem described in following picture:
<- Working, but shortening to three decimals. (And rounding up, which is done mathematically correct)
And then the problems: (Right-most picture is correct)
As you can see, the bottom image just ignores the decimals completely. What code do I need to add/change for this to work properly?
Here is the relevant code:
[super viewDidLoad];
_convertFrom = #[#"MTPA", #"MMcf/day",
#"Mill.Sm3/day", #"MMBTU/day", #"Boe/day",#"ton LNG/day", #"GJ/day"];
_convertTo = #[#"MTPA", #"MMcf/day",
#"Mill.Sm3/day", #"MMBTU/day", #"Boe/day", #"ton LNG/day", #"GJ/day"];
_convertRates = #[ #1.0f, #133.3333333f, #3.775579545f,
#137333.3333f, #23747.68013, #1716.17252, #147247.6022];
//some place down in the code:
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
[self updateConversionLabel];
}
- (void)updateConversionLabel
{
float convertFrom = [[_convertRates objectAtIndex:[picker selectedRowInComponent:0]] floatValue];
float convertTo = [[_convertRates objectAtIndex:[picker selectedRowInComponent:1]] floatValue];
NSNumberFormatter *fmt = [NSNumberFormatter new];
float input = [fmt numberFromString:inputText.text].floatValue;
float to = convertTo;
float from = convertFrom;
float convertValue = input;
float relative = to / from;
float result = relative * convertValue;
NSString *convertFromName = [_convertFrom objectAtIndex:[picker selectedRowInComponent:0]];
NSString *convertToName = [_convertFrom objectAtIndex:[picker selectedRowInComponent:1]];
NSNumber *inputNumber = [[NSNumber alloc ]initWithFloat:convertValue];
NSNumber *resultNumber = [[NSNumber alloc]initWithFloat:result];
NSNumberFormatter *formatterResult = [[NSNumberFormatter alloc] init];
formatterResult.numberStyle = NSNumberFormatterDecimalStyle;
NSNumberFormatter *formatterInput = [[NSNumberFormatter alloc] init];
formatterInput.numberStyle = NSNumberFormatterDecimalStyle;
NSString *formattedResultString = [formatterResult stringFromNumber:(NSNumber*)resultNumber];
NSString *formattedInputString = [formatterInput stringFromNumber:(NSNumber*)inputNumber];
NSString *formelString = [[NSString alloc]initWithFormat:
#" %# %# =", formattedInputString, convertFromName];
formelLabel.text = formelString;
NSString *resultString = [[NSString alloc]initWithFormat:
#" %# %#",formattedResultString, convertToName];
resultLabel.text = resultString;
}
I'd assume the problem/fix is in this code.
EDIT: Fixed, here is how I did it for future reference:
NSNumber *inputNumber = [[NSNumber alloc ]initWithDouble:convertValue];
NSNumber *resultNumber = [[NSNumber alloc]initWithDouble:result];
NSNumberFormatter *formatterResult = [[NSNumberFormatter alloc] init];
formatterResult.numberStyle = NSNumberFormatterDecimalStyle;
NSNumberFormatter *formatterInput = [[NSNumberFormatter alloc] init];
formatterInput.numberStyle = NSNumberFormatterDecimalStyle;
[formatterResult setNumberStyle:NSNumberFormatterDecimalStyle];
[formatterResult setMaximumFractionDigits:6];
[formatterInput setNumberStyle:NSNumberFormatterDecimalStyle];
[formatterInput setMaximumFractionDigits:6];
//These four lines are the one fixing the issue.
NSString *formattedResultString = [formatterResult stringFromNumber: (NSNumber*)resultNumber];
NSString *formattedInputString = [formatterInput stringFromNumber:(NSNumber*)inputNumber];
NSString *formelString = [[NSString alloc]initWithFormat:
#" %# %# =", formattedInputString, convertFromName];
formelLabel.text = formelString;
NSString *resultString = [[NSString alloc]initWithFormat:
#" %# %#",formattedResultString, convertToName];
resultLabel.text = resultString;
Real arithmetic is precise. Any computer arithmetic has limited range - how many digits can be represented; and in the case of fractions inaccuracies due to the use of decimal factions by us humans and binary fractions by computers.
In your code you are using float which is a 32-bit binary floating point number with an precision of around 6 decimal digits and a range roughly from 10^-38 to 10^38. Your numbers are up to 9 digits.
Try using double thoughtout (and doubleValue etc.) which is a 64-bit binary floating point with a precision of around 15 decimal digits. You may still find the numbers don't come out as you wish, and for that you will need to look more into how to format numbers, but you should get the precision you are after.
If you need more precision, and decimal floating point as well, look at NSDecimalNumber.
See 32-bit floating point and 64-bit floating point for more details.

sum quantity of dictionaries in array

I have a NSArray containing a list of NSDictionary. Like:
NSArray *array = ...;
NSDictionary *item = [array objectAtIndex:0];
NSLog (#"quantity: %#", [item objectForKey: #"quantity"]);
How can I sum all the quantities contained in all dictionaries of the array?
I think you can try KVC
NSMutableArray *goods = [[NSMutableArray alloc] init];
NSString *key = #"quantity";
[goods addObject:#{key:#(1)}];
[goods addObject:#{key:#(2)}];
[goods addObject:#{key:#(3)}];
NSNumber *sum = [goods valueForKeyPath:#"#sum.quantity"];
NSLog(#"sum = %#", sum);
If you call valueForKey: on an array it gives you an array of all the values for that key, so [array valueForKey:#"quantity"] will give you an array which you can loop over and sum all the values.
NSMutableArray *quantityArray = [item objectForKey: #"quantity"];
int total =0;
for(int i=0;i<[quantityArray count];i++)
{
total+= [quantityArray objectAtIndex:i];
}

Objective-c convert NSString into NSInteger

I've got this little problem. When I have a string "3 568 030" and I use [myString intValue]; it gives me result just 3, the problem is I want to convert the whole number into int/nsinteger. The string always contains just the number if that's any help. I tried using replaceoccurencesofstring (or what is the name) and it somehow didn't work...Thanks
Do:
NSString *str = #"3 568 030";
int aValue = [[str stringByReplacingOccurrencesOfString:#" " withString:#""] intValue];
NSLog(#"%d", aValue);
output
3568030
That is because of the spaces on your string you will have to remove the whitespaces first like this:
NSString *trimmedString = [myString stringByReplacingOccurrencesOfString:#" " withString:#""];
NSInteger *value = [trimmedString intValue];
My guess is that you're using stringByReplacingOccurencesOfString:: wrongly.
//Remove spaces.
myString = [myString stringByReplacingOccurencesOfString:#" " withString #""];
int myNumber = [myString intValue];
First, remove all the whitespaces in your original string using :
NSString *trimmedString = [yourOriginalString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Then, you can convert it to an int/NSInteger. beware: using [myString intValue] will cast your string to an int, but [myString integerValue] will cast it to a NSInteger.
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:#"42"];
[f release];

finding a number in array

I have an Array {-1,0,1,2,3,4...}
I am trying to find whether an element exist in these number or not, code is not working
NSInteger ind = [favArray indexOfObject:[NSNumber numberWithInt:3]];
in ind i am always getting 2147483647
I am filling my array like this
//Loading favArray from favs.plist
NSString* favPlistPath = [[NSBundle mainBundle] pathForResource:#"favs" ofType:#"plist"];
NSMutableDictionary* favPlistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:favPlistPath];
NSString *favString = [favPlistDict objectForKey:#"list"];
NSArray *favList = [favString componentsSeparatedByString:#","];
//int n = [[favList objectAtIndex:0] intValue];
favArray = [[NSMutableArray alloc] initWithCapacity:100];
if([favList count]>1)
{
for(int i=1; i<[favList count]; i++)
{
NSNumber *f = [favList objectAtIndex:i];
[favArray insertObject:f atIndex:(i-1)];
}
}
That's the value of NSNotFound, which means that favArray contains no object that isEqual: to [NSNumber numberWithInt:3]. Check your array.
After second edit:
Your favList array is filled with NSString objects. You should convert the string objects to NSNumber objects before inserting them in favArray:
NSNumber *f = [NSNumber numberWithInt:[[favList objectAtIndex:i] intValue]];