converting an int to a string in Objective-C while preserving '0' - iphone

I am trying to convert an int to a string in objective-C.
I read the other questions on SO about converting ints to strings, and I tried this method in my code:
-(void)setCounter:(int)count
{
counterText.text = [NSString stringWithFormat:#"%d",count];
}
However, if I want to display a number like '01' the 0 is taken out of the conversion and only '1' is displayed. Is there a workaround?

There is no such number as 01. If you write
int count = 01;
it is compiled equivalently to
int count = 1;
In fact, be careful: 07 is equivalent to 7, but 011 is equivalent to 9!
What you can do is ask stringWithFormat: to give you the zero-padding:
[NSString stringWithFormat:#"%02d",count]
should give you "02" if count is 2. To deconstruct it:
% - interpolate the next value here
0 - pad it to the width by placing zeroes on the left side
2 - width is 2 characters
d - it will be an integer. Do it now.

If you want a different format to the one shown, use it:
counterText.text = [NSString stringWithFormat:#"%02d",count];
There are a huge range of possibilities with the format string.

if any number start from 0 then Its a octal representation (0 - 7). you can add zero explictly using below line.
counterText.text = [NSString stringWithFormat:#"0%d",count];

Check out..
NSNumber +numberWithInt
and then:
NSNumberFormatter -setMinimumIntegerDigits
and then get the string representation with:
NSString -stringFromNumber

Related

Concatenating Two Integers [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
It might be the simplest Question, but at this time ,I am not getting any Idea on how to implement this.
Ok, The problem is of how to concatenate two integers.
For Eg: I want to create an integer say 0000 using two different integers 00 and 00. I tried using NSString , but I failed.
My Code is :
int num1 = 00;
int num2 = 00;
NSString *str = [NSString stringWithFormat:#"%d%d",num1,num2];
int num = [str intValue];
NSLog(#"num = %d",num); // It Logs 0 but I want 0000.
Does anyone have better Idea ?
EDIT :
Please Note that , I want to use that num to set the tag of textfield. That's why all the zeros are essential. So my main Problem starts here.
I have one tableview which contains custom cells. This custom cell has more than 10 textfields. Now I want to uniquely identify all the textfields for editing. That's why the tag for that textfield must be the integer concatenated by two values called rowNumber and textFieldNumber (means which textField out of 10.).
So my question is what I am trying to do is right or not ? And if not then give me some useful solution.
The integer data types (such as int) only store the integer value, not formatting information. Therefore you lose the number of leading zeroes (which do not affect the integer value, i.e., 0, 00, and 0000 are the same integer: zero).
If you wish to retain formatting information, you must store it separately. A simple way is to just store the string itself. Or, if you always want to have the same number of digits, then alter the formatting string:
int num1 = 0;
int num2 = 0;
NSString *str = [NSString stringWithFormat:#"%02d%02d",num1,num2];
After the above code, str will be "0000". However, converting it to int and then logging with %d formatting results in 0 once more (since 0000 and 0 are the same integer).
Edit: For the purpose of generating unique integers for tagging purposes, given a row number (rowNumber) and text field number (textFieldNumber), use a formula like:
tagNumber = rowNumber * 100 + textFieldNumber;
This way the text fields of row 0 will have numbers 0..99, those on row 1 will have 100..199, etc. If more than 100 text fields are required per row, simply multiply by a larger number, like 1000.
In integer arithmetic these values can be converted back to row and field numbers with:
rowNumber = tagNumber / 100;
textFieldNumber = tagNumber % 100;
Try to use this:
int num1 = 0;
int num2 = 0;
int num3=0;
int num4=0;
NSString *str = [NSString stringWithFormat:#"%d%d%d%d",num1,num2,num2,num3];
int num = [str intValue];
NSLog(#"num = %0*d",str.length,num);
Hope this helps you.
but dont init as like this "int num1=00" because it init "0" only in num1.
Why turn it back into an int? You should print the string you just formatted:
NSLog(#"num = %#",str);
As numbers, there is no difference between 0 and 0000. Integers only preserve the value, not the formatting (that's what strings are for).
Multiply the first integer with 100 and add the second integer to it. You should be able to print it using:
NSLog([NSString stringWithFormat:#"%04d", sum]);
which will put leading zeros.
You can pad it as :
NOTE: both the num1 and num2 must be of 2 digits. If its size increases then it wont work.
int num1 = 00;
int num2 = 00;
NSString *str = [NSString stringWithFormat:#"%d%d",num1,num2];
int num = [str intValue];
NSLog(#"num = %04d",num);
If printing is not the real issue then i guess you need a multiplication factor to set the tag
let it be 10000 and add it to some sequence no to get the unique tag value.
or you can use num as string and multiply by 10 in for loop for num.length times

formatting NSDecimalNumber issue

I'm trying to create NSDecimalNumber with simply format like: 123.00 with two fractional digits after dot, always. I tried use the NSFormatter and many other ways like converting float from string and creating then NSDecimalNumber from this string, but it's not working.
The problem is that I need only NSDecimalNumber in this format, not NSString or any other.
Thanks for any advice,
Paul
You may get idea from this.
float num = 123.1254546;
NSString *str = [NSString stringWithFormat:#"%.2f",num];
NSLog(#"%.2f %#",num,str);
I think you simply need to do Type Casting operation for Two times as bellow
float value = 123.562;
int myDigit = value;
it gives value 123 in myDigit variable
NSLog(#"MyDigit in Decimal = %d",myDigit);
Output is MyDigit in Decimal = 123
now if you want output like 123.000 then simply write as bellow
float valueWithZiro = myDigit;
NSLog(#"MyDigit with 000 == %3f",valueWithZiro);
Output is MyDigit in Decimal = 123.000
NSDecimalNumber, like NSNumber, cannot contain formatting information. The object structure simply doesn't support it. It represents a number, not the way the number is displayed.
You can convert it to a formatted NSString (which you say you don't want). But you can't do what you're asking.
You convert it to a formatted NSString using an NSNumberFormatter. It's the object that allows you to specify the decimal and thousands separators, number of decimal places to display, the currency symbol, etc.
Maybe you were looking to store a NSNumberDecimal with just two digits after the fraction?
If so NSDecimalNumberBehaviors is your friend.
I had a similar need and used the following:
self.decimalHandlingBehaviorForApp = [NSDecimalNumberHandler
decimalNumberHandlerWithRoundingMode:NSRoundUp
scale:2 raiseOnExactness:NO
raiseOnOverflow:NO raiseOnUnderflow:NO
raiseOnDivideByZero:YES];
Edit: added example of using it
// update the taxable total first
self.cartTaxableTotal = [self.cartTaxableTotal decimalNumberByAdding:itemAdded.priceOfItem
withBehavior:self.decimalHandlingBehaviorForApp];

NSString - Truncate everything after decimal point in a double

I have a double that I need only the value of everything before the decimal point.
Currently I am using
NSString *level = [NSString stringWithFormat:#"%.1f",doubleLevel];
but when given a value of 9.96, this returns "10". So it is rounding. I need it to return only the "9". (note - when the value is 9.95, it correctly returns the "9" value.)
Any suggestions?
Thank You.
Simply assign the float/double value to a int value.
int intValue = doubleLevel;
Cast that baby as an int.
int castedDouble = doubleLevel;
Anything after the . in the double will be truncated.
9.1239809384 --> 9
123.90454980 --> 123
No rounding, simple truncation.
If you want to keep it as a float:
CGFloat f = 9.99;
f = floorf(f);
there are quite a variety of floor and round implementations.
they have been around since UN*X, and are actually part of those low-level libraries, be they BSD, Posix, or some other variety - you should make yourself familiar with them.
there are different versions for different "depths" of floating point variables.
NSString *level = [NSString stringWithFormat:#"%d",doubleLevel];

How can you read 0's at the start of an integer or string? To then compare them

I am trying to code a textField so that is someone put in the number 1 only it will show up 10 and if the put in the number 01 it will show up 01.
The problem I have is that when I code an if statement it can't seem to read the 0 at the start of the number so I end up with 010 or just 1.
I have tried to use integers but get the same result and have tried == and compare for strings but nothing.
NSString *millieString = [[NSString alloc]initWithFormat:#"%#",timeFieldMillie.text];
if([millieString compare:#"01"]){
timeFieldMillie.text = [[NSString alloc]initWithString:millieString];
}
else if ([millieString compare:#"1"]){
timeFieldMillie.text = [[NSString alloc]initWithFormat:#"%#0", millieString];
}
This is probably because the first 0 is not being read but I can't seem to fix it.
I am trying to make a time converter and this is for the milliseconds so I need it to be 2 digits long.
Thanks
Use -isEqualToString: instead
You're leaking memory
The string is reset without the need to do it in your first if
Here's a simpler version:
if ([timeFieldMillie.text isEqualToString:#"1"])
timeFieldMillie.text = [NSString stringWithString:#"01"];
Or simply:
if ([timeFieldMillie.text isEqualToString:#"1"])
timeFieldMillie.text = #"01";
Have you try if ([millieString isEqualToString:#"01"])?
NSString compare return NSComparisonResult, try use isEqualToString

Performing operations on a double returns 0

I have a method that receives a number in a NSString format.
I wish to convert this string to a double which I can use to calculate a temperature.
Here's my method.
NSString *stringTemp = text; // text is a NSString
NSLog(#"%#",stringTemp); // used for debugging
double tempDouble = [stringTemp doubleValue];
NSLog(#"%f",tempDouble); // used for debugging
Please note I put the NSLog commands here just to see if the number was correct. The latter NSLog returns a value of 82.000000 etc. (constantly changes as it's a temperature).
Next I wanted to use this double and convert it to a Celsius value. To do so, I did this:
double celsiusTemp = (5 / 9) * (tempDouble - 32);
Doing this: NSLog(#"%d", celsiusTemp); , or this: NSLog(#"%f", celsiusTemp); both give me a value of 0 in the console. Is there any reason why this would be happening? Have I made a stupid mistake somewhere?
Thank you for your help!
Try doing (5.0 / 9.0). If you only use an int to do math where you are expecting a double to be returned (like 0.55) everything after the decimal place will be lost because the cpu expects an int to be returned.
5 / 9 is the division of two integers, and as such uses integer division, which performs the division normally and then truncates the result. So the result of 5 / 9 is always the integer 0.
Try:
double celsiusTemp = (5.0 / 9) * (tempDouble - 32);
If you evaulate (5/9) as an integer, then it is just 0.