Get Percentage from two integers - iphone

I am almost half way there to getting the percentage of two integers i just need help with the final hurdle, here is my coding so far below it works but sometimes its like yes = 50 and no = 20% when it should be 50/50.
int yes;
int no;
//Work out percentages
if ([VotedAnswer.text isEqualToString:#"No"]){
yes = [currentYes intValue];
no = [currentNo intValue] + 1;
}else{
yes = [currentYes intValue] + 1;
no = [currentNo intValue];
}
int total = yes + no + 1;
int pcntYes = (yes *100) / total;
int pcntNo = (no *100) / total;
float barNo = pcntNo / 100.0f;
float barYes = pcntYes / 100.0f;
//Set percent labels
yesPercent.text = [NSString stringWithFormat:#"%d%%", pcntYes];
noPercent.text = [NSString stringWithFormat:#"%d%%", pcntNo];
//Set Percent Bars
YesProgress.progress = barYes;
NoProgress.progress = barNo;

You should not be adding 1 to total. The total number of votes cast is simply yes + no.
Oh and don't forget to update currentYes and currentNo you haven't shown code that is doing that.

It works for me
int yes = [cell.yesAnswer.text intValue] ;
int no = [cell.noAnswer.text intValue];
int total = yes + no + 1;
int pcntYes = (yes *100) / total;
int pcntNo = (no *100) / total;
float barNo = pcntNo / 100.0f;
float barYes = pcntYes / 100.0f;
cell. yesProcent.text = [NSString stringWithFormat:#"%d%%", pcntYes];
cell. noProcent.text = [NSString stringWithFormat:#"%d%%", pcntNo];

Related

Unable to do calculation and get print out to label

I'm doing the following code when they hit the calculate button in my app:
float sqft = ([textfield1.text floatValue]);
float thick= ([textfield2.text floatValue]);
float cos = ([textfield3.text floatValue]);
float eff = ([textfield4.text floatValue]);
float num = ((thick*.5)*sqft)/eff;
float cost = (num*cos);
float costft = (cost/sqft);
label1.text = [NSString stringWithFormat:#"%2.f",num];
label2.text = [NSString stringWithFormat:#"%2.f",cost];
label3.text = [NSString stringWithFormat:#"%2.f",costft];
When I do this the labels only return zeros. I have set the labels to maually be strings just to see if it was a delegation thing but I can't figure out why my formulas return zeros only
The problem is with the way you have used %2.f in your code,
%2.f gives you the rounded value of the answer in 2 number format. If any of your answer is less than or equals to 0.5 . then you get 0 as the answer.
now it should work
float sqft = ([textfield1.text floatValue]);
float thick= ([textfield2.text floatValue]);
float cos = ([textfield3.text floatValue]);
float eff = ([textfield4.text floatValue]);
float num = ((thick*.5)*sqft)/eff;
float cost = (num*cos);
float costft = (cost/sqft);
label1.text = [NSString stringWithFormat:#"%2f",num];
label2.text = [NSString stringWithFormat:#"%2f",cost];
label3.text = [NSString stringWithFormat:#"%2f",costft];
Its working proper at my end . But in one case you will get ZERO value when your value is 0.786676 like that..
textfield1.text = #"123.89";
textfield2.text= #"123.00";
textfield3.text= #"123.7";
textfield4.text= #"123";
float sqft = ([textfield1.text floatValue]);
float thick= ([textfield2.text floatValue]);
float cos = ([textfield3.text floatValue]);
float eff = ([textfield4.text floatValue]);
float num = ((thick*.5)*sqft)/eff;
float cost = (num*cos);
float costft = (cost/sqft);
NSLog(#"Num : %#",[NSString stringWithFormat:#"%2.f",num]);
NSLog(#"Cost : %#",[NSString stringWithFormat:#"%2.f",cost]);
NSLog(#"Costft : %#",[NSString stringWithFormat:#"%2.f",costft]);
Output
Num : 62
Cost : 7663
Costft : 62
You want to limit the digits after the decimal point to two - that is why you are using .2f, right? If so, you should use this #"%.2f"
Just try this:
label1.text = [NSString stringWithFormat:#"%.2f",num];
label2.text = [NSString stringWithFormat:#"%.2f",cost];
label3.text = [NSString stringWithFormat:#"%.2f",costft];

2 values should be the same but aren't

I have the following code which takes a HEX code somebody entered and transforms it into HSB:
NSString *cString = [[hexText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) NSLog(#"UH OH");
// strip 0X if it appears
if ([cString hasPrefix:#"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) NSLog(#"UH OH");
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
float red = r / 255.0f;
float green = g / 255.0f;
float blue = b / 255.0f;
float colorArray[3];
colorArray[0] = red;
colorArray[1] = green;
colorArray[2] = blue;
int max;
int min;
min=0;
max=0;
for(int i=1; i<3; i++)
{
if(colorArray[i] > colorArray[max])
max=i;
if(colorArray[i] < colorArray[min])
min=i;
}
if(max==min)
{
h3=0;
s3=0;
b3=colorArray[0];
}
else
{
b3=colorArray[max];
s3=(colorArray[max]-colorArray[min])/(colorArray[max]);
if(max==0) // Red
h3 = (colorArray[1]-colorArray[2])/(colorArray[max]-colorArray[min])*60/360;
else if(max==1) // Green
h3 = (2.0 + (colorArray[2]-colorArray[0])/(colorArray[max]-colorArray[min]))*60/360;
else // Blue
h3 = (4.0 + (colorArray[0]-colorArray[1])/(colorArray[max]-colorArray[min]))*60/360;
}
I then have this code which does the opposite - transforms HSB into a hex code:
UIColor *forC = colourPreview.backgroundColor;
const CGFloat *c = CGColorGetComponents([forC CGColor]);
CGFloat r, g, b;
r = c[0];
g = c[1];
b = c[2];
if (r < 0.0f) r = 0.0f;
if (g < 0.0f) g = 0.0f;
if (b < 0.0f) b = 0.0f;
if (r > 1.0f) r = 1.0f;
if (g > 1.0f) g = 1.0f;
if (b > 1.0f) b = 1.0f;
hexWithoutHash = [NSString stringWithFormat:#"%02X%02X%02X",
(int)(r * 255), (int)(g * 255), (int)(b * 255)];
These should both give the same value, and most of the time it does. But sometimes I will type in a hex code such as 208DBC and it will return 1F8CBC. Any ideas? I think it's something to do with the second bit of code returning an inaccurate hex code, but not sure how to make this more accurate in this case?
Could be a floating-point precision issue. Using a float or a double does not store an exact value as using an int or long does. It stores the closest approximation of the exact value allowed by the IEEE-754 spec. The difference between the stored value and the exact value is generally very small, but it may be just big enough that when you convert back to an integer your value gets truncated to the next smaller integer. That is what is happening in your output (i.e. 0x1F = 0x20 - 1, 0x8C = 0x8D - 1).
The following code may illustrate the issue:
for (int redColor = 0; redColor < 256; redColor++) {
int originalRed = redColor;
float red = originalRed / 255.0f;
float redMultiplied = red * 255;
int newRed = (int)redMultiplied;
if (newRed != originalRed) {
NSLog(#"Value mismatch detected: origianlRed=%d, red=%f, redMultiplied=%f, newRed=%d",
originalRed, red, redMultiplied, newRed);
}
}

How to use a segment to select a value then use that value in a formula

I am trying to simply have a segment when selected pick a factor and use it in a formula. The problem i am having is converting the factor a (float) into a value a (double) and show this on the display. What am I doing wrong here? Seems like an easy fix but I've tried a lot of things to no avail.
.h
NSInteger segPicked, var1, var2;
.m
var1 = 1100;
var2 = 2.5;
- (void) pickOne:(id)sender { // Selector for twosegment controller
if (checkCondition == properCondition) {
segUnit.text = [twoSegments titleForSegmentAtIndex: [SixSegments selectedSegmentIndex]];
segPicked = [twoSegments selectedSegmentIndex];
float factor = 0;
if (segPicked == 0 ) {
factor = 0.28;
} else if (segPicked == 1 ) {
factor = 0.16;
}
double value = (factor*(var1/var2)); <--- It crashes here..
Result.text = [NSString stringWithFormat:#"Segment with = ", value];
}
}
check that var2 must be != 0
and:
Result.text = [NSString stringWithFormat:#"Segment with = ", value];
should be:
Result.text = [NSString stringWithFormat:#"Segment with = %f", value];
EDIT:
float factor;
NSInteger var1;
NSInteger var2;
float var2_test;
var1 = 1100;
var2 = 2.5;
var2_test = 2.5;
NSLog(#"int var2: %i, float var2_test: %f", var2, var2_test); // var2=2
factor = 0.16;
double value;
value = (factor*(var1/var2)); // Not Crashes to me!
NSLog(#"******: %f", value);
it all works good to me, no crashes, are you sure it crashes at that point?
just a consideration:
var2 = 2.5;
var2 is: 2 (it's an integer)
Division by Zero ?
Dividing two integers?
double value = (factor*(var1/var2));

How do I convert a number to hours and minutes?

I got help with correct calculation the other day but I've hit a block about how to implement it into code.
-(IBAction)done:(id)sender {
int result = (([startHours.text intValue] * 60) + [startMinutes.text intValue]) -
(([finishHours.text intValue] * 60) + [finishMinutes.text intValue]);
totalHours.text = [NSString stringWithFormat:#"%i", result / 60];
if (result < 0) {
totalHours.text = [NSString stringWithFormat:#"%d", result * -1];
}
The above is the code. However, in the text field it comes out as the total number of minutes. I want to covert it so it would show up as total hours and minutes (10.30). How would I do that in code?
If result is a time in minutes:
int minutes = result%60
int hours = (result - minutes)/60
totalHours.text = [NSString stringWithFormat:#"%d.%d", hours, minutes];
Pheelicks's answer is OK. Just two small additions: handle sign of interval before calculating parts, and use more common time format:
int result = (([startHours.text intValue] * 60) + [startMinutes.text intValue]) -
(([finishHours.text intValue] * 60) + [finishMinutes.text intValue]);
int minutes = abs(result)%60
int hours = (abs(result) - minutes)/60
totalHours.text = [NSString stringWithFormat:#"%02d:%02d", hours, minutes];
Try changing the int to a float.
-(IBAction)done:(id)sender {
float result = (([startHours.text intValue] * 60) + [startMinutes.text intValue]) -
(([finishHours.text intValue] * 60) + [finishMinutes.text intValue]);
totalHours.text = [NSString stringWithFormat:#"%2.2f", result / 60];
if (result < 0) {
totalHours.text = [NSString stringWithFormat:#"%2.2f", result * -1];
}

OBJ-C: Getting the minimum/maximum value in a NSMutableArray

I want to get the maximum and minimum values of a NSMutableArray so I can create a core-plot plotspace and graph based around those max and min values.
My code is as follows:
NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for (i=0; i<60; i++){
id x = [NSNumber numberWithFloat:i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_Max + 0.6];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, #"x", y, #"y", nil]];
}
self.dataForPlot = contentArray;
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
What do I fill in the blanks for xRange and yRange assignment if I want the graph to span only the space of what's specified in contentArray?
In this case, you should use -[CPPlotSpace scaleToFitPlots:]. For more general calculations on array values, read on...
This is an ideal use for Key-Value coding and associated array operators. In your example,
float maxX = [[contentArray valueForKeyPath:#"#max.x"] floatValue];
float minY = [[contentArray valueForKeyPath:#"#min.x"] floatValue];
float maxY = [[contentArray valueForKeyPath:#"#max.y"] floatValue];
float minY = [[contentArray valueForKeyPath:#"#min.y"] floatValue];
The array operators call valueForKeyPath: on the contentArray which gives an array built by calling the same valueForKeyPath: on each member of the array with the key path to the right of the array operator (i.e. #min and #max). The orignal call then applies the given operator to the resulting array. You could easily define a category on NSArray to give you back a struct of min/max values:
typedef struct {
float minX;
float minY;
float maxX;
float maxY;
} ArrayValueSpace;
#implementation NSArray (PlotSpaceAdditions)
- (ArrayValueSpace)psa_arrayValueSpace {
ArrayValueSpace result;
result.maxX = [[contentArray valueForKeyPath:#"#max.x"] floatValue];
result.minX = [[contentArray valueForKeyPath:#"#min.x"] floatValue];
result.maxY = [[contentArray valueForKeyPath:#"#max.y"] floatValue];
result.minY = [[contentArray valueForKeyPath:#"#min.y"] floatValue];
return result;
}
You can find max and min values when you fill it, but it would work just when used in your snippet. If you want something more generic you should simply go through the list and searching for it.
// contentArray already defined
int maxX = 0, minX = 1000, maxY = 0, minY = 1000;
for (int i = 0; i < [contentArray count]; ++1)
{
int curX = [[[contentArray objectForKey:#"x"] objectAtIndex:i] integerValue];
int curY = [[[contentArray objectForKey:#"y"] objectAtIndex:i] integerValue];
if (curX < minX)
minX = curX;
else if (curX > maxX)
maxX = curX;
if (curY < minY)
minY = curY;
else if (curY > maxY)
maxY = curY;
}
You could use fast enumeration through the array.
.
NSUInteger maxX = 0;
NSUInteger minX = 0xFFFFFFFF; //(for 32 bit)
NSUInteger maxY = 0;
NSUInteger minY = 0xFFFFFFFF; //(for 32 bit)
for ( NSDictionary *dict in contentArray )
{
NSUInteger newX = [[dict objectForKey:#"x"] integerValue];
NSUInteger newY = [[dict objectForKey:#"y"] integerValue];
if (maxX > newX) maxX = newX;
if (minX > newX) minX = newX;
if (maxY > newY) maxY = newY;
if (minY > newY) minX = newY;
}
if you have NSMutableArray of NSDictionary objects you can use this:
-(float)findMax:array arrayKey:obj {
float max = [[[array objectAtIndex:0] objectForKey:obj] floatValue];
for ( NSDictionary *dict in array ) {
if(max<[[dict objectForKey:obj] floatValue])max=[[dict objectForKey:obj] floatValue];
}
return max;
}
-(float)findMin:array arrayKey:obj {
float min = [[[array objectAtIndex:0] objectForKey:obj] floatValue];
for ( NSDictionary *dict in array ) {
if (min > [[dict objectForKey:obj] floatValue])min = [[dict objectForKey:obj] floatValue];
}
return min;
}
You would access methods like this if in another class:
GraphData *c=[[GraphData alloc] init];
float maxY=[c findMax:plotData arrayKey:[NSNumber numberWithInt:1]]; //1 or 0 depending on axis
[c release];
//This gives Max and Min Value in NSMutableArrray
-(void)FindingMinAndMaxValueInNSMutableArray{
NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:#"0.987",#"0.951",#"0.881",#"0.784",#"0.662",#"0.522",#"0.381",#"-0.265",#"-0.197", #"0.189",#"-0.233",#"0.310",#"0.402",#"0.402",#"0.988",#"0.633",#"0.661",#"0.656",#"0.617",#"0.634",#"0.690",#"0.767",#"0.836",nil];
NSLog(#"The Array Value is %#",array);
NSLog(#"The Array Count is %lu",(unsigned long)array.count);
NSNumber *maxValue = [array valueForKeyPath:#"#max.doubleValue"];
NSLog(#"The maxValue is %#",maxValue);
NSString *str=[NSString stringWithFormat:#"%#",maxValue];
NSInteger path=[array indexOfObject:str];
NSIndexPath *indexpath=[NSIndexPath indexPathForItem:path inSection:0];
NSLog(#"Max Value = %# and index = %ld",maxValue,(long)indexpath.row);
NSNumber *minValue = [array valueForKeyPath:#"#min.doubleValue"];
NSLog(#"The minValue is %#",minValue);
NSString *str1 = [NSString stringWithFormat:#"%#",minValue];
NSInteger path1 = [array indexOfObject:str1];
NSIndexPath *indexPath1 = [NSIndexPath indexPathForItem:path1 inSection:0];
NSLog(#"Min Value =%# and index = %ld",minValue,(long)indexPath1.row);
}