How do I convert an integer to the corresponding words in objective-c?
Power of extension for Swift 5
import Foundation
public extension Int {
var asWord: String? {
let numberValue = NSNumber(value: self)
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
return formatter.string(from: numberValue)
}
}
var value = 2
if let valueAsWord = value.asWord {
//do something with your worded number here
print("value worded = \(valueAsWord)")
} else {
print("could not word value :(")
}
Note: Edited to protect against formatter.string(from:
returning nil which is highly not likely, but still possible.
Output: value worded = two
Apple has a lot of handy formatting functionality built in for many data types. Called a "formatter," they can convert objects to/from string representations.
For your case, you will be using NSNumberFormatter, but if you have an integer you need to convert it to an NSNumber first. See below example.
NSInteger anInt = 11242043;
NSString *wordNumber;
//convert to words
NSNumber *numberValue = [NSNumber numberWithInt:anInt]; //needs to be NSNumber!
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
wordNumber = [numberFormatter stringFromNumber:numberValue];
NSLog(@"Answer: %@", wordNumber);
// Answer: eleven million two hundred forty-two thousand forty-three
If you'd like to learn more about formatters: https://developer.apple.com/library/content/documentation/General/Conceptual/Devpedia-CocoaApp/Formatter.html