简体   繁体   中英

Simple question about int

Ok.... This seems like a simple question but I can't find any info about it so I thought I would ask here.

I am trying to store a number (int) in a var but I need to keep the 0's before it

eg:

int x = 0001;
NSLog(@"%i",x)  // returns 1

Is it possible to make it return 0001?

I know that i can do this:

NSLog(@"%04i",x);  // returns 0001

But that is not quite the answer i am looking for because the number of 0's needs to vary.

I don't specifically need to use an int but it would need to be a whole number.

The leading 0's are insignificant, and adding them will make the number an octal literal , so you can not log them with out specifying the width. You can however specify a dynamic width to print.

int dyn_width = 4;
int x = 1;

NSLog(@"%0*i", dyn_width, x);

If you need the string, rather than the value, you need to use a string variable.

NSString *x = @"0001";
NSLog(@"%@",x);

Then when you need to do some calculations, use "[x intValue]".

Beside using a string, which you don't want, the only way I can see to code the number of 0s before the first significant digit is to store the value in a double , as 0.0001 . Of course in some cases, precision might be an issue, not mentioning that arithmetic on that style of integer representations becomes more difficult.

I would argue that the number of zeroes you're trying to display is not part of your model (the actual backing store, the int ), but of the presentation (so a function taking your int and displaying it somehow).

Regardless, elementary math teaches us that 1 is the same number as 01 , so you'll have a hard time convincing the computer any differently.

You've got two options - create an object that both holds the int-value (1) the padding-count (3) and the padding type (zeros), or use a string. Using a string can cause other problems later (validation, can you stop other parts of the code putting string data like text in there?)

But, the real question is, why do you want this.. surely there's another way? Code refactor time!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM