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

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

Related

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

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

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

Removing characters after the decimal point for a double

How can I remove the all the characters after the decimal point.
Instead of 7.3456, I would just like 7.
This is what I do to get the number so far with decimal places.
[NSString stringWithFormat:#" %f : %f",(audioPlayer.currentTime),(audioPlayer.duration) ];
Many Thanks,
-Code
You can specify what you want using format string :
[NSString stringWithFormat:#" %.0f : %.0f", (audioPlayer.currentTime),
(audioPlayer.duration)];
If you want this for display, use an NSNumberFormatter:
double sevenpointthreefourfivesix = 7.3456;
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithDouble:sevenpointthreefourfivesix]]);
2011-12-20 20:19:48.813 NoDecimal[55110:903] 7
If you want a value without the fractional part, use round(). If you want the closest integer value not greater than the original value, use floor().
floorf() is the function you're looking for.
you are after
[NSString stringWithFormat:#" %.00f : %.00f",(audioPlayer.currentTime),(audioPlayer.duration) ];
When formatting float you can tell the precision by the number before the f
Cast to int:
[NSString stringWithFormat:#" %i : %i",(int)(audioPlayer.currentTime),(int)(audioPlayer.duration) ];
Casting like this always rounds down (eg: just removes everything after the decimal place). This is what you asked for.
In the case of rounding to the NEAREST whole number you want to add 0.5 to the number
[NSString stringWithFormat:#" %i : %i",(int)(audioPlayer.currentTime+0.5f),(int)(audioPlayer.duration+0.5f) ];
This will round to the nearest whole number. eg: 1.2 becomes 1.7 and casting to int makes 1. 3.6 becomes 4.1 and casting makes 4. :)
Why not just cast the audioPlayer.currentTime to an integer before you use stringWithFormat?
[NSString stringWithFormat:#"%d", (int)(audioPlayer.currentTime)];
All you need to do is type-cast the double to an int, like so: int currentTime_int = (int)audioPlayer.currentTime;.
You can use this same approach for the other variable.
Many of the shorter answers here will work correctly. But if you want your code to be really clear and readable, you might want to explicitly specify your desired conversion from float to int, such as using:
int tmpInt = floorf(myFloat); // or roundf(), etc.
and then separately specifying how you want the integer formated, e.g.
... stringWithFormat:#"%d", tmpInt ... // or #"%+03d", etc.
instead of assuming that an inline cast shows what you want.
You may also use
double newDvalue =floor(dValue);
it will remove all the decimals point
using %.0f for string format will be good also

Weird behavior with UILabel and Text propert

Im trying to do something that I think is super simple.
i have 3 integers - prevgues1 , 2 and 3
and i have 3 UILabels prevguess1, 2 and 3
the ints have 1 less s.
When I set the text of the label so
prevguess1.text = [NSString stringWithFormat:#"%d", prevguess1]
prevguess2.text = [NSString stringWithFormat:#"%d", prevguess2];
prevguess3.text = [NSString stringWithFormat:#"%d", prevguess3];
the label just set to a number like 89324 or something like that.
I just don't know what my problem is.
Any ideas would be helpful
Cheers
Sam
Note:
I have tried setting the text simply to a string - and have had luck.
but when i set it to a integer, which start as 0 value, (in viewdidload) the weirdness happens
prevguess1.text = [NSString stringWithFormat:#"%d", prevguess1];
Here you treat prevguess1 as a label and as an integer - probably there's a typo somewhere?
Even if it's not a matter of your problems I think you should consider changing the way you name your variables a bit to avoid possible confusion.

Code to generate random strings creates same succession of identical strings

I have the following method that should create a 20 character ID (sometimes with a prefix) and return the ID.
It seems to reset on launch and every time I use it it will create the same succession of identical numbers.
+(NSString *)createUniqueIdentifier:(NSString *)withPrefix {
NSString *outstring = nil;
if (withPrefix!=nil && ![withPrefix isEqualToString:#""]) {
outstring = [withPrefix stringByAppendingString:#"-"];
} else {
outstring = #"";
}
NSInteger ii;
NSString *allletters = #"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (ii=0; ii<20; ii++) {
outstring = [outstring stringByAppendingString:[allletters substringWithRange:[allletters rangeOfComposedCharacterSequenceAtIndex:random()%[allletters length]]]];
}
return outstring;
}
I'm assuming this has something to do with random(), but I don't know what else to use. I think I even got that suggestion from Stack Overflow.
Thanks for any help!
When using random() you should set the seed value at program start, ie srandom(time(NULL));
My guess is that you probably need to set the seed since it'll use a default one if you don't.
You should at least use something based on the date/time to get something that varies for each run.
If you'd like a completely unique string, I'd use NSProcessInfo to generate one for you by calling:
[[NSProcessInfo processInfo] globallyUniqueString];
Unless you only want it to contain those letters mentioned.
I think I've figured it out. I changed random() to arc4random() and it magically seems to work now.
Here's the documentation on arc4random that probably has something to do with it:
The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (21700) states. The arc4random() function returns pseudo-random numbers in the range of 0 to (232)-1, and therefore has twice the range of rand(3) and random(3) .
The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via arc4random_addrandom().
There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically initializes itself.
FYI: If you absolutely need unique strings, create a UUID instead of using random, which has a minute chance of getting identical values.