gossainapps
gossainapps

Reputation: 803

How to pad an integer with zeroes to the right of the integer?

I know that to pad an integer with zeroes I can do the following,

NSString *version = [NSString stringWithFormat:@"%03d", appVersion.intValue];

This will add up to 3 zeroes to the left of the integer if needed. However I would like to do the same but instead of padding to the left, I need to pad to the right.

How can I pad an integer with zeroes but to the right of the integer? (Ideally with similar simplicity as the above method)

Here's an example of what I need,

If the integer turns out to be 38, I need the version string to come out as 380 (Only one zero was added to the end of the integer because I wanted a max of three characters and if the integer is less than three characters, zeroes will be added to make it three).

The method I am currently using will give me 038. I need 380.

Or if the integer is 381 then the output should be 381 because I only want a max of three character.

Upvotes: 1

Views: 305

Answers (2)

Alex Reynolds
Alex Reynolds

Reputation: 96937

Can you multiply the value by 1000, and then print that? If you need a lot of zeroes, you might generally want to promote the int to a long or long long before multiplying, to reduce the likelihood of overflow.

NSString *version = [NSString stringWithFormat:@"%ld", ((long)appVersion.intValue)*1000];

If you need the length of the int in digits, before deciding to multiply by some factor of ten, take the floor of the decimal log of the value and add one. For example:

int foo = 123;
int digitsInFoo = floor(log10(foo)) + 1; /* 3 */

Then use some rule to decide how many zero digits to add.

int totalDesiredLength = 5;
int numberOfZeroesNeeded = totalDesiredLength - digitsInFoo; /* this assumes totalDesiredLength >= digitsInFoo */
int factor = (int) pow(10, numberOfZeroesNeeded); /* 100 */

Then the five-digit result will be foo * factor or 12300. You can adjust this for your situation as needed. Test for bounds so that you don't end up with weird results.

Upvotes: 5

Pete Becker
Pete Becker

Reputation: 76245

char buf[4];
int len = sprintf(buf, "%u", 38);
while (len < 3)
    buf[len++] = '0';
buf[len] = '\0';

You might prefer sprint_s over sprintf. And if you're really paranoid, check that the value returned from sprintf isn't negative.

Upvotes: 0

Related Questions