- Storing Numbers in Collections
- Performing Decimal Arithmetic
- Converting Between Strings and Numbers
- Reading Numbers from Strings
Converting Between Strings and Numbers
From: strtonum.m
6int answer = [@"42" intValue];
7NSString *answerString =
8[NSString stringWithFormat: @"%d", answer];
9NSNumber *boxedAnswer =
10[NSNumber numberWithInt: answer];
11NSCAssert([answerString isEqualToString:
12[boxedAnswer stringValue]],
13@"Both strings should be the same");
There are several ways of converting between a number and a string. A lot of objects that represent simple data have methods like -intValue, for returning an integer representation of the receiver.
NSString has several methods in this family. If you have a string that contains a numerical value, you can send it a -doubleValue, -floatValue, -intValue, or -longLongValue message to convert it to any of these types. In 64-bit safe versions of Foundation, you can also send it an -integerValue message. This will return an NSInteger.
There are a few ways of going in the opposite direction, getting a string from an integer. We look at one in Chapter 6: The +stringWithFormat: method on NSString lets you construct a string from any primitive C types, just as you would construct a C string with sprintf().
If you already have a number in an NSNumber instance, there are two ways of getting a string, one of which is a wrapper around the other. The -descriptionWithLocale: method returns a string generated by formatting the number according to the specified locale.
In fact, this doesn't do the translation itself. It sends an -initWithFormat:locale: message to a new NSString. The format string depends on the type of the number: for example, a double will be converted using the @ "%0.16g" format string. This uses up to 16 significant figures and an exponent if required.
The decimal separator depends on the locale. If you send an NSNumber a -stringValue message, this is the equivalent to sending a -descriptionWithLocale: message with nil as the argument. This uses the canonical locale, which means without any localization, so the result will be the same on any platform.