arc4random: limit the value of the random number generated - ios

Built an iPhone app that generates a random number to a label when a button is pressed.
It works fine, but any value I put doesn't seem to limit the value of the random number generated. it's always 9 digits.
-(IBAction)genRandnum:(id)sender {
NSNumber *randomNumber = [NSNumber numberWithInt: (arc4random() % 5) + 1];
NSNumber *randomLabeltxt = [[NSString alloc] initWithFormat:#"It worked!", randomNumber];
randLabel.text = [NSString stringWithFormat: #"%d", randomLabeltxt];
[randomLabeltxt release];
}
As you can see, I've put 5 in after the % sign, but it generates 9 digit numbers.

NSNumber is an Objective-C object, therefore you should use %# to display it. %d shows a 9 digit number as that's the address of that NSNumber.
NSString is not the same as an NSNumber.
The correct and simplified code should look like:
int randomNumber = (arc4random() % 5) + 1;
// no need to create an NSNumber if you do not need to store it into an NS container.
randLabel.text = [NSString stringWithFormat:#"It worked! %d", randomNumber];
// no need to create an intermediate NSString variable.
// you can directly assign the string to the label's text.

Related

Split double-digit NSInteger into Two NSIntegers

I am trying to figure out how to take a double-digit NSInteger on iOS (like 11) and turn it into 2 separate NSIntegers, each looking like "1". It will always be just 2 digits in the NSInteger, no more, no less, and no decimals.
You can simply use integer/modulo arithmetic
int tensDigit=originalNumber / 10;
int onesDigit=originalNumber % 10;
NSInteger a=11;
NSInteger b=a%10;
NSInteger c=(a-b)/10;
NSLog(#"%# %# %#",a,b,c);
You can simply divide by 10 and find the reminder of division by 10.
NSNumber* number = [NSNumber numberWithInt:21];
NSNumber* partOne = [NSNumber numberWithInt:([number integerValue] / 10)];
NSNumber* partTwo = [NSNumber numberWithInt:([number integerValue] % 10)];
for 21, partOne will be 2 and partTwo will be 1.
In general, for any number n, ith digit is n % pow(10, i)
use this it work (In Swift).
var number = 36
var tenPlace = number / 10
var UnitPlace = number % 10
see the Screen shot.

How to not show unnecessary zeros when given integers but still have float answers when needed

I have an app I'm developing and one of my features is giving answers in float or double values when needed and an integer when the answer is a whole number
so for example if the answer comes out to 8.52 the answer becomes 8.52 but when the answer is 8 the answer is 8 instead of 8.0000, i don't want it to show all the extra 0s.
- (IBAction) equalsbutton {
NSString *val = display.text;
switch(operation) {
case Plus :
display.text= [NSString stringWithFormat:#"%qi",[val longLongValue]+[storage longLongValue]];
case Plus2 :
display.text= [NSString stringWithFormat:#"%f",[val doubleValue]+[storage doubleValue]];
this code doesn't seem to work
These specifiers are standard IEEE format specifiers, which means that you can do things like %.2f to only show 2 decimal places on a float variable.
You could also convert it into an int, and then use the %d format specifier if you wanted to do it that way.
Here's also Apple's documentation on the subject.
EDIT: Based on your comment on the other post, it looks like you're looking for %g, which will essentially remove the extraneous 0's from floats.
display.text= [NSString stringWithFormat:#"%g",[val doubleValue]+[storage doubleValue]];
I found the answer here: Use printf to format floats without decimal places if only trailing 0s
EDIT Formatting
Here is a way that I did this when I needed to display currency (but whole numbers if the currency was a round number.
First we get the money amount as a string
NSString *earnString = _money.payout.displayableAmount;
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:earnString.length];
//scan the string to remove anything but the numbers (including decimals points)
NSScanner *scanner = [NSScanner scannerWithString:earnString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
//create an int with this new string
int earnInt = [strippedString intValue];
//if the string is less than 100 then we only had "change" so display that amount
if(earnInt < 100){
//Dollar amount is less then dollar display just the cents and the cent symbol
NSString *centString = [NSString stringWithFormat:#"%i¢", earnInt];
earnAmount.text = centString;
//if we have a number evenly divisible by 100 then we have whole dollar amount, display that properly
}else if(earnInt % 100 == 0){
//The amount is exactly a dollar, display the whole number
NSString *wholeDollar = [NSString stringWithFormat:#"$%i", (earnInt/100)];
earnAmount.text = wholeDollar;
//finally if we have a mixed number then put them back together with the decimal in-between.
}else{
//Dollar amount is not exactly a dollar display the entire amount
NSString *dollarString = [NSString stringWithFormat: #"$%0d.%02d", (earnInt / 100), (earnInt % 100)];
earnAmount.text = dollarString;
}
Hopefully this helps you out...
You can try this method call:
[NSString stringWithFormat:#"%.0f", [val doubleValue] + [storage doubleValue]];
Easiest way, is NSNumberFormatter. It will only display the decimal if needed. Example (Swift):
let num1: Double = 5
let num2: Double = 5.52
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .DecimalStyle
print(numberFormatter.stringFromNumber(NSNumber(double: num1)))
print(numberFormatter.stringFromNumber(NSNumber(double: num2)))
This will print 5 and then 5.52.

ios: NSLog show decimal value

NSNumber *weekNum = [dictionary valueForKey:#"inSeasonFor"];
NSDecimalNumber *newWeekNum = ([weekNum intValue] *2)/4;
NSLog(#"%", [newWeekNum decimalValue]);
How can I divide weekNum*2 by 4 and keep the decimal value and print it?
You mean you want the fractional part as well, right?
NSNumber *weekNum = [dictionary valueForKey:#"inSeasonFor"];
// multiplication by 2 followed by division by 4 is division by 2
NSLog(#"%f", [weekNum intValue] / 2.0f);
//we can also use intfloat to resolve.

Custom Formatting A String Value For Text Label

In my project, I have a function that runs and spits out a 5 digit number into a label on my interface. The number can be a double or a float but I would like it to display like ###+##.##
Example Number 12345.67
Shown like 123+45.67
The output will always be a 5 digit number with decimals. I researched data formatting specifically number formatting but haven't come across anything specific for this case. This is where I change the number to a string and assign it to a label. Please help and thank you in advance for your time.
NSString *outputNumber = [NSString stringWithFormat:#"%f",numberHere];
_stationing.text = outputNumber;
There are a couple of ways this could be done.
NSMutableString *outputNumber = [[NSString stringWithFormat:#"%.2f", numberHere] mutableCopy];
[outputNumber insertString:#"+" atIndex:outputNumber.length - 5];
_stationing.text = outputNumber;
Another:
int high = numberHere / 100;
float low = numberHere - (high * 100);
NSString *outputNumber = [NSString stringWithFormat:#"%d+%.2f", high, low];
These approaches won't work well if the number is less than 100.
Hope this help
NSStirng *numberString = [NSString stringWithFormat:#"%.2f",numberHere];
NSString *firstPart = [numberString substringWithRange:NSMakeRange(0, 3)];
NSString *secondPart [numberString substringWithRange:NSMakeRange(3, 5)];
NSString *outputString = [NSString stringWithFormat:#"%#+%#", firstPart, secondPart];
If the number's format is not permanent, you should check the length first.

Set UILabel character limit?

I have a UILabel that shows the outside temperature, the problem is, sometimes it shows it as a XX.XXº format instead of the normal XXº or XXXº format used to show temperature, is there anyway to force the label to only show the temperature without the decimals or at least force it to only be able to use 2 characters?
You can use this to eliminate the decimals:
NSString* numberString = [NSString stringWithFormat:#"%.0f", d]; // 0 means no decimals
Otherwise I believe this will work to limit the number of chars to 2:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.usesSignificantDigits = YES;
formatter.maximumSignificantDigits = 2;
I have not really used NSNumberFormatter very much though.
NSString *temp = [galleryEntryTree objectForKey:#"description"];
if ([temp length] > 500) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 500}];
temp = [temp substringWithRange:range];
temp = [temp stringByAppendingString:#" …"];
}
coverView.label2.text = temp;
You may also use substring method
NSString *newformat = [NSString stringWithFormat:#"%#",[temperature substringWithRange:NSMakeRange(0,2)]];
In this case temperature is a string that you set for your label and you are only retrieving the 1st 2 digits only

Resources