NSString “three” to “3”, etc.

I posted a question to the apple developer list which received a wonderful answer. My question was basically how can I transform a string with a spelled-out number as the numeric equivalent. “Three” becomes “3”, “twelve” becomes “12”, etc. without writing an enormous string replacement method. Well… check this out… this won’t localize (I don’t think) but it’s remarkable.

NSNumberFormatter * nf = [NSNumberFormatter new];
[nf setNumberStyle: NSNumberFormatterSpellOutStyle];
NSLog(@"Survey Says...%@", [nf numberFromString:string]);
//Yields "Survey Says...3"
//Works with "seventy-three" and "thirteen point five" too!

Check that out… it’s meant to go from “3” to “three” – but if you feed it the opposite way it works too! nil is returned for things it can’t convert, like “dozen”. This an incredible discovery.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.