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.
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
intto alongorlong longbefore multiplying, to reduce the likelihood of overflow.If you need the length of the
intin digits, before deciding to multiply by some factor of ten, take thefloorof the decimallogof the value and add one. For example:Then use some rule to decide how many zero digits to add.
Then the five-digit result will be
foo * factoror12300. You can adjust this for your situation as needed. Test for bounds so that you don’t end up with weird results.