Reputation: 319
I currently have an int value that is custom formatted and displayed in a label. The int value is always a 5 digit number and I display it with a + symbol between the tenths and hundredths place. If number = 12345, displayNumber = 123+45.
ViewController.m
int high = number / 100;
int low = number - (high * 100);
NSString *displayNumber = [NSString stringWithFormat:@"%d+%d", high, low];
My problem is when number has a zero in the tenths place. If number = 12304, displayNumber will display as 123+4 where I want it to display as 123+04. I've tried using an if statement for low < 10 but that doesn't incorporate well with the rest of my code. Is there any simple way to make low display two digits even if it's a one digit number? Thank you in advance for your time.
Upvotes: 2
Views: 270
Reputation: 319
The following code holds the tenths place for the particular situation when it equals zero. Ex. number = 12304, displayNumber = 123+04. I did not optimize it like dasblinkenlight suggested. Thanks dasblinkenlight!
int high = number / 100;
int low = number - (high * 100);
NSString *displayNumber = [NSString stringWithFormat:@"%d+%02d", high, low];
Upvotes: 0
Reputation: 726539
Try this:
NSString *displayNumber = [NSString stringWithFormat:@"%d+%02d", high, low];
// ^^
// ||
// |+-- Two positions
// +--- Pad with zeros
The statement
int low = number - (high * 100);
can be optimized as
int low = number % 100;
You can also skip temporary variables altogether:
NSString *displayNumber = [NSString stringWithFormat:@"%d+%02d", number/100, number%100];
Upvotes: 6