Yesterday, I showed you in this article on how to do basic math in Objective-C (and it could work in other languages as well).
Now today, I am going to show you a unique feature that you can put inside your apps – how to convert a standard number such as 934 and have the app convert them to letters – such as “nine hundred thirty four“.
But why would we need this? Well, let’s say you were writing a app to write out checks. You would need the app to print the spelled out version of an amount that a user would input in to a text field, or you’re writing an app that actually says a number to a user using speech.
For this we use a little known command called NSNumber. We use it to format a number and then tell NSNumber how to format the number for final output to the user.
Again, this is a basic example. For more complexed output, do a search on Google.com.
Let’s take a look at the below code:
NSNumber *value = [NSNumber numberWithInt:534];
NSNumberformatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterSpellOutStyle];
NSLog(@”Numeric: %@\nText: %@”,value,[formatter stringFromNumber:value]);
[NSNumberformatter release];
Now, let’s take a look at the code:
1. Assign NSNumber the variable “value” and initialize it with the number 534.
2. Call the NSNumber formatter to get it ready to format the output to a user.
3. Set the value *formatter to the NSNumberformatter command.
4. Use the formatter value to tell the computer how to format the number.
5. Print the result to the terminal.
6. Release the NSNumberFormatter from memory.
That’s it. Happy coding!