NSString to NSNumber : what am I doing wrong here? - iphone

I am executing this code:
NSLog(#"Converting line number %# to int...",currentValue);
NSNumber * currentNumber = [NSNumber numberWithInt:[currentValue integerValue]];
NSLog(#"Converted integer %d",currentNumber);
Which outputs this:
Converting line number 211 to int...
Converted integer 62549488
What am I doing wrong here ? In this case, currentValue is a NSMutableString with value of 211.

"currentNumber" is and object, which you're trying to print with %d.
NSLog(#"Converted integer %d", [currentNumber intValue]);

Although your question has already been answered there is something else wrong with your code.
There are differences between Cocoa methods with int and integer in their names.
The ones with int such as numberWithInt or intValue deal with int s.
The ones with integer such as numberWithInteger or integerValue deal with NSInteger s.
This might be a source of errors and inconsistency when programming 32/64-bit programs.
Just something to be aware of and consistent with.

NSNumber is inherited NSObject class.Its not an Integer.So you can use "%#" instead of %d.
You change your NSLog line as follows,
NSLog(#"Converted integer %#",currentNumber);

Related

Removing characters after the decimal point for a double

How can I remove the all the characters after the decimal point.
Instead of 7.3456, I would just like 7.
This is what I do to get the number so far with decimal places.
[NSString stringWithFormat:#" %f : %f",(audioPlayer.currentTime),(audioPlayer.duration) ];
Many Thanks,
-Code
You can specify what you want using format string :
[NSString stringWithFormat:#" %.0f : %.0f", (audioPlayer.currentTime),
(audioPlayer.duration)];
If you want this for display, use an NSNumberFormatter:
double sevenpointthreefourfivesix = 7.3456;
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithDouble:sevenpointthreefourfivesix]]);
2011-12-20 20:19:48.813 NoDecimal[55110:903] 7
If you want a value without the fractional part, use round(). If you want the closest integer value not greater than the original value, use floor().
floorf() is the function you're looking for.
you are after
[NSString stringWithFormat:#" %.00f : %.00f",(audioPlayer.currentTime),(audioPlayer.duration) ];
When formatting float you can tell the precision by the number before the f
Cast to int:
[NSString stringWithFormat:#" %i : %i",(int)(audioPlayer.currentTime),(int)(audioPlayer.duration) ];
Casting like this always rounds down (eg: just removes everything after the decimal place). This is what you asked for.
In the case of rounding to the NEAREST whole number you want to add 0.5 to the number
[NSString stringWithFormat:#" %i : %i",(int)(audioPlayer.currentTime+0.5f),(int)(audioPlayer.duration+0.5f) ];
This will round to the nearest whole number. eg: 1.2 becomes 1.7 and casting to int makes 1. 3.6 becomes 4.1 and casting makes 4. :)
Why not just cast the audioPlayer.currentTime to an integer before you use stringWithFormat?
[NSString stringWithFormat:#"%d", (int)(audioPlayer.currentTime)];
All you need to do is type-cast the double to an int, like so: int currentTime_int = (int)audioPlayer.currentTime;.
You can use this same approach for the other variable.
Many of the shorter answers here will work correctly. But if you want your code to be really clear and readable, you might want to explicitly specify your desired conversion from float to int, such as using:
int tmpInt = floorf(myFloat); // or roundf(), etc.
and then separately specifying how you want the integer formated, e.g.
... stringWithFormat:#"%d", tmpInt ... // or #"%+03d", etc.
instead of assuming that an inline cast shows what you want.
You may also use
double newDvalue =floor(dValue);
it will remove all the decimals point
using %.0f for string format will be good also

NSNumber stored in NSUserDefaults

Something weird just happened.
I stored a NSNumber with an unsigned long long value in NSUserDefaults. When I retrieve it, the value just changed. It seems that system thinks the number is long long instead of unsigned long long.
What's worse is that when I compare the number retrieved from UserDefaults with the original number, the result is NotEqual!
what's wrong with the code? Thank you!
static NSString * const NumberKey = #"MyNumber";
unsigned long long value = 15908045869032883218ULL;
if ([[NSUserDefaults standardUserDefaults] objectForKey:NumberKey] == nil) {
NSNumber *number = [NSNumber numberWithUnsignedLongLong:value];
[[NSUserDefaults standardUserDefaults] setObject:number forKey:NumberKey];
NSLog(#"Original Number:%#", number); // 15908045869032883218, right
}
NSNumber *number = [[NSUserDefaults standardUserDefaults] objectForKey:NumberKey];
NSLog(#"Current Number:%#", number); // -2538698204676668398, weird
NSLog(#"Current Value:%llu", [number unsignedLongLongValue]); // 15908045869032883218, right
NSLog(#"%d", [number isEqualToNumber:[NSNumber numberWithUnsignedLongLong:value]]); // 0
NSLog(#"%d", [number unsignedLongLongValue] == value); // 1
To further answer your question. If you look in the documentation for NSNumber's isEqualToNumber: function you will notice the following line,
Two NSNumber objects are considered equal if they have the same id values or if they have equivalent values
it's important you understand this. In your code you are asking is my NSNumber object "number" equal to "value", you are not asking does the numerical value stored within my NSNumber object "number" equal the numerical value stored within my NSNumber object "value".
The last line of code you have written shows that in fact your NSNumber's numerical values are in fact equal.
NSLog(#"%d", [number unsignedLongLongValue] == value); //1
So you are correctly storing and retrieving the values, you should be using the == comparison method with NSNumber objects stored numerical values (ie intValue == intValue, unsignedLongLongValue == unsignedLongLongValue) and not comparing their object id's together.
As for this line of code
NSLog(#"Current Number:%#", number); // -2538698204676668398, weird
This is not weird, this is perfectly normal, as you have told NSLog to print out an NSObject representation of 'number'. I'm not 100% certain but I believe that NSNumber's - ( NSString * ) description function defaults to return an unsigned int value for the numerical value it contains. This is why you are getting the large negative number returned. You may want to look at NSNumber's - (NSString *)descriptionWithLocale:(id)aLocale function to print out the data in a more logical for for you, or you could use
NSLog(#"Current Number:%llu", [number unsignedLongLongValue]);
Which will give you the right answer.
EDIT:
Further to this, after looking into the issue what is happening is that on recollection of your NSNumber object from UserDefaults it's original number type is not being preserved (this information is highlighted in the documentation for NSNumber in the overview section)
(Note that number objects do not necessarily preserve the type they are created with.)
You can see this yourself if you log the following after retrieving "number" from user defaults (add this to the end of the code you have in your question) and have a look at the encoding values shown here
NSLog(#"%s", [number objCType]); //This will log out q
NSLog(#"%s", [[NSNumber numberWithUnsignedLongLong:value] objCType]); //this will log out Q
The difference between Q and q is that Q is an unsigned value... hence why you are having issues with the isEqualToNumber: function as the number types are different.
If you are so dead set on using the iSEqualToNumber: function to compare values then you could implement this to retrieve your value from NSUserDefaults.
NSNumber *number = [NSNumber numberWithUnsignedLongLong:[[NSUserDefaults standardUserDefaults] objectForKey:NumberKey] unsignedLongLongValue]];
You could look at using the NSNumber compare: function to see if the returned value is NSOrderedSame however this will not work for comparing unsigned vs signed values of the same type so in your situation I'd use the above as retrieving the data from NSUserDefaults is stripping the "signedness" of your number.
At the end of the day if you want to store NSNumber into NSUserDefaults this code works for me even for large integers like: 881217446193276338
To save:
[[NSUserDefaults standardUserDefaults] setObject:self.myUser.sessionid forKey:#"sessionid"];
[[NSUserDefaults standardUserDefaults] synchronize];
To recover:
self.myUser.sessionid = (NSNumber *)[[NSUserDefaults standardUserDefaults] objectForKey:#"sessionid"];
It's storing it correctly, nothing is wrong with your code except:
NSLog(#"Current Number:%#", number);
Here number is a non-string object, you might think of it as a wrapper for a numerical primitive. Or you might think that NSNumber instances objectify a primitive type.
What you need is some thing like:
NSLog(#"Current Number:%#", [number stringValue]);
Here is a speculative answer:
The NSNumber documentation states that:
(Note that number objects do not necessarily preserve the type they are created with.) .
So it must be using a different internal storage for this type, and only gives you the correct value when you specifically ask for the unsigned long long value. The description method, which is called in your NSLog statement, may be defaulting to a different representation type.
And / or there may be some quirk of the unarchiver that is preventing the isEqualToNumber method working on the value returned from defaults. If you do that comparison between two NSNumbers created in the same scope, does it work? The correct value is definitely in there somewhere given your last statement returns true.

Objective C convert number to NSNumber

Why doesn't this please the compiler? Casting is supposed to work like in C as I can read here How to cast an object in Objective-C.
[p setAge:(NSNumber*)10];
where
- (NSNumber*) age {
return _age;
}
- (void) setAge: (NSNumber*)input {
[_age autorelease];
_age = [input retain];
}
In a sort of symmetry with your earlier question, NSNumber is an object type. You need to create it via a method invocation such as:
[p setAge:[NSNumber numberWithInt:10]];
Your current code is attempting simply to cast the arbitrary integer 10 to a pointer. Never do this: if the compiler didn't warn you about it, you would then be trying to access some completely inappropriate bytes at memory location 10 as if they were an NSNumber object, which they wouldn't be. Doing that stuff leads to tears.
Oh, and just to preempt the next obvious issues, remember that if you want to use the value in an NSNumber object, you need to get at that via method calls too, eg:
if ( [[p age] intValue] < 18 )
...
(NSNumber is immutable, and I think it is implemented such that identical values are mapped to the same object. So it is probably possible to get away with direct pointer comparisons for value equality between NSNumber objects. But please don't, because that would be an inappropriate reliance on an implementation detail. Use isEqual instead.)
Today it is also possible to do it using shorthand notation:
[p setAge:#(10)];
Use this:
[p setAge:[NSNumber numberWithInt:10]];
You can't cast an integer literal like 10 to a NSNumber* (pointer to NSNumber).
NSNumber *yourNumber = [NSNumber numberWithInt:your_int_variable];
Because NSNumber is an object and "10" in a primitive integer type, much like the difference between int and Integer in Java. You, therefore, need to call its initialiser:
[p setAge:[NSNumber numberWithInt:10]

Why isn't the NSNumber class correctly converting my NSString object to a long long?

I'm trying to convert an NSString object to an NSNumber with the same numerical value. When I create the NSString object using this statement...
NSString *songID = [localNotif.userInfo objectForKey:#"SongID"];
the var songID contains the string value #"10359537395704663785". and when I attempt to convert it to an NSNumber object using the statement...
NSNumber *songIDNumber = [NSNumber numberWithLongLong:[songID longLongValue]];
the var songIDNumber contains the wrong value of 9223372036854775807
What am I doing wrong? It might also be worth noting that sometimes this code does work and produce the correct NSNumber value, but most of the time it fails as shown above.
Thanks in advance for your help!
UPDATE: God I love this site! Thanks to unbeli and carl, I was able to fix it using the updated code for converting from the NSString to the NSNumber...
unsigned long long ullvalue = strtoull([songID UTF8String], NULL, 0);
NSNumber *songIDNumber = [NSNumber numberWithUnsignedLongLong:ullvalue];
longLongValue returns LLONG_MAX in case of overflow, and LLONG_MAX is exactly what you get, 9223372036854775807. You value simply does not fit in long long
Try using NSDecimalNumber instead.
9223372036854775807 decimal is 0x7FFFFFFFFFFFFFFF in hex. Your number is 10359537395704663785, which is too large for a long long and overflows. From the NSString documentation:
Returns LLONG_MAX or LLONG_MIN on overflow.

objective-c converting strings to usable numbers

I have strings that look about like this:
stringA = #"29.88";
stringB = #"2564";
stringC = #"12";
stringD = #"-2";
what is the best way to convert them so they can all be used in the same mathmatical formula?? that includes add, subtract.multiply,divide etc
Probably floatValue (as it appears you want floating-point values), though integerValue may also be of use (both are instance methods of NSString).
[stringA doubleValue]
These are all wrong, because they don't handle errors well. You really want an NSNumberFormatter.
If you have the string #"abc" and try to use intValue or floatValue on it, you'll get 0.0, which is obviously incorrect. If you parse it with an NSNumberFormatter, you'll get nil, which is very easy to distinguish from an NSNumber (which is what would be returned if it was able to parse a number).
Assuming that you have NSString variables.
NSString *stringA = #"29.88";
NSString *stringB = #"2564";
NSString *stringC = #"12";
NSString *stringD = #"-2";
suppose, you want to convert a string value to float value, use following statement.
float x=[stringA floatValue];
suppose, you want to convert a string value to integer value, use following statement.
NSInteger y = [stringC intValue];
Hope, it helps to you.