FizzBuzz
FizzBuzz

Reputation: 764

Is it possible to spell out numbers in words with a separator?

I'm aware of NSNumberFormatter's NSNumberFormatterSpellOutStyle, but that returns poorly formatted numbers: 932 returns "nine hundred thirty-two" rather than "nine-hundred and thirty-two".

In a different question Dave DeLong said that he got "nine hundred and thirty-two" for the same code, which is exactly what I want - the word "and" (or whatever that may be when localized) used to separate large numbers. Is this possible?

Upvotes: 0

Views: 485

Answers (1)

rdelmar
rdelmar

Reputation: 104082

If you just want the "and" added, I think you'll have to do it manually (either the behavior has changed since the question you referenced was answered, or that was a typo in the answer). I think you could do it this way, but I don't know if this will work in all situations that you want it to:

    int num = 932;
    int leftNum = floor(num/100) * 100;
    int rightNum = num % 100;
    NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterSpellOutStyle];
    NSString *combo;
    if (num > 100) {
        NSString *l = [f stringFromNumber:[NSNumber numberWithInt:leftNum]];
        NSString *r = [f stringFromNumber:[NSNumber numberWithInt:rightNum]];
        combo = [NSString stringWithFormat:@"%@ and %@",l,r];
    }else{
        combo = [f stringFromNumber:[NSNumber numberWithInt:num]];
    }
    NSLog(@"%@", combo);

Upvotes: 3

Related Questions