Problem when converting NSString to NSNumber in iPhone - iphone

I am having problem when converting string (YaxisData) to NSNumber. I have to return a NSNumber for Core-plot to get the graph done but its not working. Here's the sample code
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSNumber *num = [NSNumber numberWithDouble:[[YaxisData objectAtIndex:index] doubleValue]];
return num;
}
num returns junk data such as -1 or 993494949494 but when I log the double value of number, it prints the correct value. I am not able to return this double value as the function signature requires only the NSNumber to be returned.
NSLog(#"Number: %f", [num doubleValue]);
I am stuck here and would really appreciate any help in this regard. Thanks!

Would this give a better result somehow?
NSString *aString = [YaxisData objectAtIndex:index];
NSLog(#"%#", aString);
double value = [aString doubleValue];
NSLog(#"%f", value);
NSNumber *number = [NSNumber numberWithDouble:value];
NSLog(#"%#", number);
If not, could you show the results of the NSLog()'s?
I know that in practice it seems the same code, yet one might not be so sure that -objectAtIndex: always returns a string. It might be a localization issue as well (commas and dots for decimal separator might get mixed up, this would definitely mess up your results. In case of a localization issue, check the following link:
How to convert an NSString into an NSNumber

Related

Xcode Gives Strange Output From NSArray

When I run this code, the output is some 1084848 to the console. I can't figure out why such odd output... here is the code.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
int someNumber = 3;
[array addObject:[NSNumber numberWithInt:someNumber]];
NSLog(#"%i" , [array objectAtIndex:0]);
[pool drain];
return 0;
}
the "%i" format specifier expects an integer, not an Object.
Try NSLog(#"%i" , [[array objectAtIndex:0] intValue]);
XCode is probably giving you a warning on this line: something like "Conversion specifies type 'int', but argument has type 'id'".
Here's the pseudocode of your program:
//
// Inside of your main function....
//
// Set up the Autorelease pool and then create an array
//
// Declare an int
//
// Add the int to an array, while wrapping it in an NSNumber
//
// Log the value of the first object in the array, using the int formatter
//
// Clean up and return
//
You are logging the first object in the array, but NSArray cannot hold a primitive that's not wrapped in an Objective-C object.
To better understand your code, try changing these lines of code:
int someNumber = 3;
[array addObject:[NSNumber numberWithInt:someNumber]];
Expand them a little. Try this:
int someNumber = 3;
NSNumber *aNumber = [NSNumber numberWithInt:someNumber];
[array addObject:aNumber];
So, you've correctly wrapped the int in an NSNumber, but you're not unwrapping it. You need to ask your NSNumber for the int that it holds like so:
[[array objectAtIndex:0] intValue];
Or, to do the logging in one line:
NSLog(#"%i" , [[array objectAtIndex:0] intValue]);
The characters "%i" is called a "formatter". Different kinds of values require different formatters. When you are using an Objective-C object, you use "%#". For an NSInteger or int, you'd use %i. For a float, you'd use "%f". The point is that you need to either unwrap that number, or use the Objective-C formatter for strings.
A quick note about that weird value you were getting earlier: That's a memory address in RAM. It's the closest thing you're going to get when you use an incorrect formatter. In some cases, using the wrong formatter will cause an EXC_BAD_ACCESS. You were "lucky" and got a weird value instead of a dead program. I suggest learning about strings and formatters before you move on. It will make your life a lot easier.
When you use %i for integer values then you should give arguments as integer as below
NSLog(#"%i" , [[array objectAtIndex:0] intValue]);
But when you want object to be displayed then you must use %# which identifies object in general case as below:
NSLog(#"%#", array);

Display NSNumber In Label

I am trying to display an NSNumber from an array with keys into an UILabel. Here is my current code: marblesNeeded.text = [[[records objectAtIndex:0] valueForKey: #"marblesneeded"] intValue];
I also get the error:
warning: Semantic Issue: Incompatible integer to pointer conversion assigning to 'NSString *' from 'int'
Thanks
You need to create an NSString to set the text of a UILabel.
marblesNeeded.text = [NSString stringWithFormat:#"%i",[[[records objectAtIndex:0] valueForKey: #"marblesneeded"] intValue]];
In the format %i denotes that you will be providing an integer value after the format.
Edit:
As some comments have noted NSNumber does have a stringValue, it does work but is not my personal preference because it gives you little control as to the format of the string. Consider this example.
NSNumber *number = [NSNumber numberWithFloat:3.25];
NSLog(#"%#",number.stringValue); // Will print 3.25
NSLog(#"%#",[NSString stringWithFormat:#"%i",number.intValue]); // Will print 3
Since the question envolved printing an intValue this more explicit format may be necessary.
marblesNeeded.text = [[[records objectAtIndex:0] valueForKey: #"marblesneeded"] stringValue];

Unable to convert string value into float

when i convert a string value into float it takes o.oooo. here is the code.
NSString *amt=txtTotalBill.text;
NSLog(#"%#",amt);
float amount = [amt floatValue]
NSLog(#"%f",amount);
NSString *insertData=[NSString stringWithFormat:#"insert into tbl_Bills(Amount,Note,Due_On) values ('%f')",amount];
[database executeQuery:insertData];
NSLog(#"inert query: %#",insertData);
NSLog(#"value inserted");
[table reloadData];
[database close];
everytime it takes amount as 0.0000.In this code amt value is correct but that string value doesnt convert into float.
just tried some of your codeblock and it works out fine for me. The error could be in the NSString itself. Perhaps its not passing in a totally numerical number. Try using a CGFloat as well, although this shouldn't change anything.
I assume you've alreayd ensured that no non-numeric characters can make their way into the NSString thats to be converted.
Can you let us know whats the output you got for the NSLog for the string?
Could you also try setting an output format for the float? e.g. '%3.3f' will display 3 numbers each before and after the decimal point.
Check txtTotalBill.text if the text is float number format.
If text is not float number format, [NSString floatValue] retuns 0.00000
Try this, i think this will work.
float amount = [txtTotalBill.text floatValue];
This works perfect
NSString *amt = txtTotalBill.text;
float amount;
amount = [amt floatValue];

nsmutablearray float object returns a zero

In the root model I have:
[self.rPrices replaceObjectAtIndex:0
withObject:[NSNumber numberWithFloat:(float)nR4]];
NSLog(#"%.2f", [self.rPrices objectAtIndex:0]);
where rPrices is NSMutableArray.
nR4 is not zero but the above NSLog(...); displays zero.
Thanks
Try this
NSLog(#"%.2f", [[self.rPrices objectAtIndex:0] floatValue]);
or alternativly just print the NSNumber as an object
NSLog(#"%#", [self.rPrices objectAtIndex:0]);
NSNumber is an object. So you can't print it using float format specifier "%f".
You can use "%#" or get the float value from it using -floatValue and print it using "%f".

Nsnumber out of scope problem

I am trying to make NSNumber *percent to get the integer value percentint but it keeps making it out of scope.. The Nslog logs are like this:
The value of integer num is 4
The value of integer num is with NsNumber
78910432
My code is this:
In my header file:
int percentint;
NSNumber *percent;
#property(nonatomic,retain) NSNumber *percent; //tried without using this too
In my .m file:
#synthesize percent; //tried without using this too
percentint=4;
NSLog(#"The value of integer num is %i", percentint);
percent= [NSNumber numberWithInt:percentint];
percent= [[NSNumber alloc] initWithInt:percentint]; //tried without using this too.
[percent autorelease]; //tried without using this too.
NSLog(#"The value of integer num is with NsNumber %i", percent);
Try:
percentint=4;
NSLog(#"The value of integer num is %i", percentint);
self.percent= [NSNumber numberWithInt:percentint];
NSLog(#"The value of integer num is in array %#", self.percent);
NSLog(#"The value of integer num is in array %d", [self.percent intValue]);
leaving the #synthesize percent; in.
User #Felz is correct. in order to get the value of a NSNumber, you must retrieve it with a method call:
int percentInt = 95;
NSNumber *percent = [NSNumber numberWithInt:percentInt];
int myint = [percent intValue];
What you did instead, was print out the pointer address for percent
NSLog(#"Percent Value: %d",[percent intValue]);
NSLog(#"Percent Address: 0x%X",percent);
Remember that NSNumber *percent means percent is a pointer not a value.
Like the other user insinuated, NSNumber is not an integer as you are trying to call it in the last NSLog. to get the int value out of a NSNumber, use [percent intValue].
Another side note: you don't need to initialize percent twice. The first call numberWithInt: is like doing an alloc/init/release.
Also, never release an object before you are done with it.