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",开发者_Go百科 @"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.
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 NSNumber
s (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);
精彩评论