The following table lists the methods from NSNumber.
#import <Foundation/Foundation.h>
int main ()
{
NSNumber *myNumber;
myNumber = [NSNumber numberWithFloat:3.47];
NSLog (@"The value in NSNumber = %@", myNumber);
return 0;
}
The code above generates the following result.
The following code shows how to use NSNumber to multiply two numbers and returns the product.
#import <Foundation/Foundation.h> @interface SampleClass:NSObject - (NSNumber *)multiplyA:(NSNumber *)a withB:(NSNumber *)b; @end @implementation SampleClass - (NSNumber *)multiplyA:(NSNumber *)a withB:(NSNumber *)b { float number1 = [a floatValue]; float number2 = [b floatValue]; float product = number1 * number2; NSNumber *result = [NSNumber numberWithFloat:product]; return result; } @end int main() { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; SampleClass *sampleClass = [[SampleClass alloc]init]; NSNumber *a = [NSNumber numberWithFloat:10.5]; NSNumber *b = [NSNumber numberWithFloat:10.0]; NSNumber *result = [sampleClass multiplyA:a withB:b]; NSString *resultString = [result stringValue]; NSLog(@"The product is %@",resultString); [pool drain]; return 0; }
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { float fNumber = 12; NSString *floatToString = [NSString stringWithFormat:@"%f", fNumber]; NSLog(@"floatToString = %@", floatToString); NSNumber *number = [NSNumber numberWithFloat:30]; NSString *numberToString = [number stringValue]; NSLog(@"numberToString = %@", numberToString); return 0; }
The code above generates the following result.
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSString *aFloatValue = @"12.50"; float f = [aFloatValue floatValue]; float result = f * 2 + 45; NSLog(@"f = %f and result = %f", f, result); NSNumber *aFloatNumber = [NSNumber numberWithFloat:[aFloatValue floatValue]]; NSLog(@"aFloatNumber = %@", aFloatNumber); return 0; }
The code above generates the following result.
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSNumber *numberToFormat = [NSNumber numberWithFloat:9.99]; NSLog(@"numberToFormat = %@", numberToFormat); NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle; NSLog(@"Formatted for currency: %@", [numberFormatter stringFromNumber:numberToFormat]); numberFormatter.numberStyle = NSNumberFormatterSpellOutStyle; NSLog(@"Formatted for spelling out: %@", [numberFormatter stringFromNumber:numberToFormat]); return 0; }