floats in NSArray - objective-c

I have an NSArray of floats which I did by encapsulating the floats using
[NSNumber numberWithFloat:myFloat] ;
Then I passed that array somewhere else and I need to pull those floats out of the array and perform basic arithmatic. When I try
[myArray objectAtIndex:i] ;
The compiler complains that I'm trying to perform arithmatic on a type id. It also won't let me cast to float or double.
Any ideas? This seems like it should be an easy problem. Maybe it will come to me after another cup of coffee, but some help would be appreciated. Thanks.

You can unbox the floats like this:
float f = [[myArray objectAtIndex:i] floatValue];

Unbox the float value from the NSNumber object thusly:
NSNumber *number = myArray[i];
float f = [number floatValue];

Your are converting float value to NSNumber object and adding it to NSArray.So you have to again convert NSNumber object to float value.
NSNumber *number = [yourArray objectAtIndex:0];
float f = [number floatValue];

Related

How to get result?

hello! Sorry for my question. I hope you'll ask and help me.
I want to get result with this code:
NSNumber *first = #10;
NSNumber *second = #30;
NSNumber *resultTest = first + second;
But Xcode got a error, unfortunately. How to add the variables with class NSNumber?
I know I can with this way:
int first = 10;
int second = 20;
int result = first + second;
But how to do it with class NSNumber?
Sorry again. I am newbie in Objective-C programming. Thank you.
You can convert NSNumber to int, sum the numbers, then convert back to NSNumber.
NSNumber *result = [NSNumber numberWithInt:([first intValue] + [second intValue])];
NSNumber isn't designed to be used in calculations. It's main usage is to wrap primitive (numeric) types so that they can be used in contexts where you need an object---typically for storing them in a collection such as an NSArray.
That being said, the following will work:
NSNumber *first = #10;
NSNumber *second = #30;
NSNumber *third = #([first integerValue] + [second integerValue]);

getting 0.0000 when converting NSString value to float

In my application, i tried to convert NSString value to float using
NSString *value = [dict objectForKey:#"student_Percentage"];
float f = [value floatValue];
But I'm getting the value of f as 0.00000. I tried with NSNumberFormatter, NSNumber... but still get 0.00000.
floatValue returns 0.0 if the receiver doesn’t begin with a valid
text representation of a floating-point number.
[dict objectForKey:#"student_Percentage"] value should be like 8.9.
Remove double quotes from your string.
NSMutableString *value = [dict objectForKey:#"student_Percentage"];
[value replaceOccurrencesOfString:#"\"" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [value length])];
float f = [value floatValue];
Hey i think your dict value has a problem. Try this code it gives the correct value.
NSString *temp = #"25.38";
float p = [temp floatValue];
NSLog(#"%f",p);
Or maybe use valueforkey instead of objectForKey.

How can I create an NSArray with float values

I want to make a float value array. How can I do this? My code is:
NSArray *tmpValue = [[NSArray alloc] init];
total = total + ([[self.closeData objectAtIndex:i]floatValue] - total)* expCarpan;
firstValue = total;
NSArrays only take object types. You can add various non-object types to an NSArray by using the NSNumber wrapper:
NSNumber *floatNumber = [NSNumber numberWithFloat:myFloat];
[myArray addObject:floatNumber]; // Assuming `myArray` is mutable.
And then to retrieve that float from the array:
NSNumber *floatNumber = [myArray objectAtIndex:i];
float myFloat = [floatNumber floatValue];
(As you have done in your code above).
Update:
You can also use the NSValue wrapper in the same way as NSNumber for other non-object types, including CGPoint/Size/Rect/AffineTransform, UIOffset/EdgeInsets and various AV Foundation types. Or you could use it to store pointers or arbitrary bytes of data.
The NSArray class can only contain instances of other Objective-C objects. Fortunately, Apple already has several Objective-C object types for encapsulating C primitive types. For instance, NSNumber can incapsulate many different types of C numbers (integers, floats, etc.). NSValue can incapsulate arbitrary structures, CGPoints, pointers, etc. So, you can use NSNumber and float in conjunction with NSArray as follows:
NSArray * myArray;
NSNumber * myFloatObj = [NSNumber numberWithFloat:3.14];
myArray = [NSArray arrayWithObjects:myFloatObj, nil];
You can then get the original float value from the first NSNumber of the array:
NSNumber * theNumber = [myArray objectAtIndex:0];
float theFloat = [theNumber floatValue];
Alternatively, you can turn this into a one-liner:
float theFloat = [[myArray objectAtIndex:0] floatValue];
Primitive types can't be included in a NSArray, which is only for objects. For numbers, use NSNumber to wrap your floats.
NSNumber *n1 = [NSNumber numberWithFloat:1.2f];
NSNumber *n2 = [NSNumber numberWithFloat:1.4f];
NSArray *array = [NSArray arrayWithObjects:n1, n2, nil];

Add up all values from NSMutableArray

I have a NSMutableArray, containing x different NSStrings (NSString but only numbers no letters). I would like to add up all of the values to return a single float, or int. I think I have to do this with a for loop, but i am very unfamiliar with for loops....
OK I have reached this point:
for (NSString *a in det)
{
float x = [a floatValue];
NSLog(#"%.2f",x);
}
And this returns all the values like this in ´NSLog`:
23.00
8.00
61.00
...
How could i just add them up now?
You can avoid looping and instead use the key value coding and obtain the total
NSMutableArray *arr = [NSMutableArray arrayWithObjects:#"1.1", #"2.2", #"3.1", nil];
NSNumber *sum = [arr valueForKeyPath:#"#sum.floatValue"];
Variable sum will be 6.4.
Try this:
float total = 0;
for(NSString *str in det)
{
total += [str floatValue];
}
Here is the code for a for-in if you want to save a bit of typing. It's preferable to use fast enumeration for these types of scenarios with data structures that support it.
float result = 0.0;
for(NSString *i in nsArray)
{
result += [i floatValue];
}
int result = 0;
for(int i=0;i<[array count];i++)
result += [[array objectAtIndex:i] intValue];
if you need to return a float simply define result as float and use floatValue instead of intValue

How do I access floats from a dictionary of floats?

I have a property list (Data.plist) that contains an array of two dictionaries. Each dictionary is filled with key names (Factor 1, Factor 2, etc) and floats (0.87, 1.15, etc.). I am trying to access the numbers stored in the dictionary. First I load the dictionary using:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"Data.plist"];
NSArray *plistData = [[NSArray arrayWithContentsOfFile:finalPath] retain];
NSDictionary *dictionaryOne = [plistData objectAtIndex:0];
Actually accessing the numbers stored is where I'm having a problem:
Float32 conversionFactor = [scyToLCMMen objectForKey:"Factor 50"];
I'm getting the error: "incompatible types in initialization". What am I doing wrong? Is it not a Float32?
Objective-c containers can only hold obj-c types, so what you get is not a float for sure. What you probably have is NSNumber object and you need to "extract" plain float value from it:
Float32 conversionFactor = [[scyToLCMMen objectForKey:"Factor 50"] floatValue];
NSNumber *conversionFactor = [dictionaryOne valueForKey:#"Factor 50"];
float factor = [conversionFactor floatValue];
That's what I'd do
The value is likely an instance of NSNumber.
Float32 conversionFactor = [[scyToLCMMen objectForKey:"Factor 50"] floatValue];