shah1988
shah1988

Reputation: 2684

Convert a numeric value in a string to integer in Objective C/C

I have a NSString with me. This NSString is obtained from a Voice engine. The voice input is converted to native NSString. See the following string: "Set heat to thirty two degree"

Is there any way to get this converted to "Set heat to 32 degree"

If there are some third party library that does this conversion, it would be really helpful. Otherwise I will have to create a complex logic to get this done it seems.

Upvotes: 2

Views: 225

Answers (1)

akashivskyy
akashivskyy

Reputation: 45220

And that's where a forgotten NSNumberFormatter can show what it's capable of doing.

After you parsed your input string (using regular expression magic or NSString's componentsSeparatedByString:, I'll not be discussing that step) and obtained the spell-out number, you can use NSNumberFormatter's NSNumberFormatterSpellOutStyle to quickly convert your string into a number:

NSString *obtainedDegreesString = @"thirty-two";
NSNumberFormatter *spellOutFormatter = [[NSNumberFormatter alloc] init];
[spellOutFormatter setLocale:[NSLocale currentLocale]]; // or whatever locale you want
[spellOutFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
NSNumber *degreesNumber = [spellOutFormatter numberFromString:obtainedDegreesString];
NSLog(@"%d", degreesNumber.intValue); // logs 32

But warning - you have to convert strings like "thirty two" to "thirty-two" (the correct English numerals) for your formatter to work - passing "thirty two" results in 3002! Your users probably don't want to burn in 3002 degrees :P You can achieve that using another regular expression, I suppose.

Upvotes: 3

Related Questions