1

I have a string, length may vary but I have to check if its length is less then 12 and if yes append those many zeros to it.

Like:

  • str = Test123, output should be Test12300000

  • str = Test123456, output should be Test12345600

Only 12 Char is allowed in string.

Tried below code but not getting generic result. There must be a better and easy way to do.

- (NSString *)formatValue:(NSString *)str forDigits:(NSString *)zeros {
    return [NSString stringWithFormat:@"%@%@", str ,zeros]; 
} 
user2813740
  • 517
  • 1
  • 7
  • 29

2 Answers2

2

how about something like this:

- (NSString *)stringToFormat:(NSString *)str {
    while (str.length <12) {
        str = [NSString stringWithFormat:@"%@0", str];
    }

    return str;
}
Serj
  • 696
  • 5
  • 17
1

This is fast and simple, I think.

- (NSString *)stringToFormat:(NSString *)str {
    return [str stringByAppendingString:[@"000000000000" substringFromIndex:str.length]];
}

Just make sure the string is never more than 12 characters.

LGP
  • 4,135
  • 1
  • 22
  • 34