Split double-digit NSInteger into Two NSIntegers - ios

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.

Related

Concatenate a NSInteger to NSInteger

i'm making my own calculator and i came to the question.
Sorry for newbie question , but I didn't find it.
How can i append a NSInteger to another NSInteger in Objective-C;
for example:
5 + 5 = 55
6 + 4 + 3 = 643
etc.
You have to convert them to strings. Here's one way:
NSNumber *i1 = #6;
NSNumber *i2 = #4;
NSNumber *i3 = #3;
NSMutableString *str = [NSMutableString new];
[str appendString:[i1 stringValue]];
[str appendString:[i2 stringValue]];
[str appendString:[i3 stringValue]];
NSLog(#"result='%#", str);
However, having said all that, it's not clear to me why you are concatenating at all.
If they are a single digit (as in a calculator) you can simply do:
NSInteger newNumber = (oldNumber * 10) + newDigit;
or in a method:
- (NSInteger)number:(NSInteger)currentNumber byAdding:(NSInteger)newDigit {
//Assumes 0 <= newDigit <= 9
return (currentNumber * 10) + newDigit;
}
If they have more than one digit you can make them into strings, concatenate them and convert back to integers or use simple arithmetic to find out the power of 10 you must multiply by.
EDIT: 6 + 4 + 3 Assuming a digit is provided at a time:
NSInteger result = [self number:[self number:6 byAdding:4] byAdding:3];
Purely arithmetic solution:
- (NSInteger)powerOfTenForNumber:(NSInteger)number {
NSInteger result = 1;
while (number > 0) {
result *= 10;
number /= 10;
}
return result;
}
- (NSInteger)number:(NSInteger)currentNumber byAdding:(NSInteger) newNumber {
return (currentNumber * [self powerOfTenForNumber:newNumber]) + newNumber;
}

Is there any easy way to round a float with one digit number in objective c?

Yes. You are right. Of Course this is a duplicate question. Before flag my question, please continue reading below.
I want to round a float value, which is
56.6748939 to 56.7
56.45678 to 56.5
56.234589 to 56.2
Actually it can be any number of decimal precisions. But I want to round it to nearest value. (If it is greater than or equal to 5, then round up and if not, then round down).
I can do that with the below code.
float value = 56.68899
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
[numberFormatter setMaximumFractionDigits:1];
[numberFormatter setRoundingMode:NSNumberFormatterRoundUp];
NSString *roundedString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:value]];
NSNumber *roundedNumber = [NSNumber numberFromString:roundedString];
float roundedValue = [roundedNumber floatValue];
Above code looks like a long process. I have several numbers to round off. So this process is hard to convert a float value into NSNumber and to NSString and to NSNumber and to float.
Is there any other easy way to achieve what I asked ?
I still have a doubt in the above code. It says roundUp. So when it comes to roundDown, will it work?
Can't you simply multiply by 10, round the number, then divide by 10?
Try
CGFloat float1 = 56.6748939f;
CGFloat float2 = 56.45678f;
NSLog(#"%.1f %.1f",float1,float2);
56.7 56.5
EDIT :
float value = 56.6748939f;
NSString *floatString = [NSString stringWithFormat:#"%.1f",floatValue];
float roundedValue = [floatString floatValue];
NSString* strr=[NSString stringWithFormat: #"%.1f", 3.666666];
NSLog(#"output is: %#",strr);
output is:3.7
float fCost = [strr floatValue];
This works for me
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setMinimumFractionDigits:0];
CGFloat firstnumber = 56.6748939;
NSString *result1 = [formatter stringFromNumber:[NSNumber numberWithFloat:firstnumber]];
NSLog(#"RESULT #1: %#",result1);
CGFloat secondnumber = 56.45678;
NSString *result2 = [formatter stringFromNumber:[NSNumber numberWithFloat:secondnumber]];
NSLog(#"RESULT #2: %#",result2);
CGFloat thirdnumber = 56.234589;
NSString *result3 = [formatter stringFromNumber:[NSNumber numberWithFloat:thirdnumber]];
NSLog(#"RESULT #2: %#",result3);
You don't want float, because that only gives you six or seven digits precision. You also don't want CGFloat, because that only gives you six or seven digits precision except on an iPad Air or iPhone 5s. You want to use double.
Rounding to one digit is done very simply:
double x = 56.6748939;
double rounded = round (10 * x) / 10;
You can use
[dictionaryTemp setObject:[NSString stringWithFormat:#"%.1f",averageRatingOfAllOrders] forKey:#"AvgRating"];
%.1f will give us value 2.1 only one digit after decimal point.
Try this :
This will round to any value not limited by powers of 10.
extension Double {
func roundToNearestValue(value: Double) -> Double {
let remainder = self % value
let shouldRoundUp = remainder >= value/2 ? true : false
let multiple = floor(self / value)
let returnValue = !shouldRoundUp ? value * multiple : value * multiple + value
return returnValue
}
}

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.

how to round off NSNumber and create a series of number in Object C

May i know how to round up a NSNumber in object C ?
for(int i=6; i>=0; i--)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed];
[dayArray addObject:dayString];//X label for graph the day of drink.
drinksOnDay.isDetailViewHydrated = NO;
[drinksOnDay hydrateDetailViewData];
NSNumber *sdNumber = drinksOnDay.standardDrinks;
[sdArray addObject: sdNumber];
}
inside this sdArray are all the numbers like this 2.1, 1.3, 4.7, 3.1, 4.8, 15.1, 7.2;
i need to plot a graph Y axis so i need a string of whatever is from the NSNumber to show
a NSString of this {#"0", #"2", #"4", #"6", #"8", #"10", #"12",#"14",#"16"}. as i need to start from zero, i need to determine which is the biggest number value. in this case it will be 15.1 to show 16 in the graph. instead of doing a static labeling, i will like to do a dynamic labeling.
what you have seen in the graph is static numbering not dynamic.
i'm sorry for missing out the important info.
thanks for all the comments
Check out the math functions in math.h, there's some nice stuff there like
extern double round ( double );
extern float roundf ( float );
As for the rest of your question you probably have to parse your strings into numbers, perform whatever action you want on them (rounding, sorting, etc) then put them back into strings.
Your edit now makes a lot more sense. Here is an example of getting all even numbers from your 0 to your max value in your NSArray of NSNumbers (assuming all values are positive, could be changed to support negative values by finding minimum float value as well).
NSArray *sdArray = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:2.1],
[NSNumber numberWithFloat:1.3],
[NSNumber numberWithFloat:4.7],
[NSNumber numberWithFloat:3.1],
[NSNumber numberWithFloat:4.8],
[NSNumber numberWithFloat:15.1],
[NSNumber numberWithFloat:7.2],
nil];
//Get max value using KVC
float fmax = [[sdArray valueForKeyPath:#"#max.floatValue"] floatValue];
//Ceiling the max value
int imax = (int)ceilf(fmax);
//Odd check to make even by checking right most bit
imax = (imax & 0x1) ? imax + 1 : imax;
NSMutableArray *array = [NSMutableArray arrayWithCapacity:(imax / 2) + 1];
//Assuming all numbers are positive
//(should probably just use unsigned int for imax and i)
for(int i = 0; i <= imax; i +=2)
{
[array addObject:[NSString stringWithFormat:#"%d", i]];
}
NSLog(#"%#", array);

arc4random: limit the value of the random number generated

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.

Resources