Question

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.

Was it helpful?

Solution

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];

OTHER TIPS

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top