adding total sum with floating points - ios

In xcode I am utilizing 4 utitextfields for the following chart that the user will enter a whole number, chart is the following:
Total | Win | Place | Show
34 | 4 | 5 | 3
My algorithm for this chart is the following:
-For total win * 1
-For total place * .5
-For total Show * .25
-Add the three totals into a new Float value (identified as,
float totalTrackAllTogether)
-Divide totalTrackAllTogether by the total column (identified as,
int trackTotalColum)
-Display the sum on onOffLabel.text
Here is the code portion that does not seem to work and crashes
-(void)trackRecordMath
{
int trackWinColum = [trackWin.text intValue];
int trackPlaceColum = [trackPlace.text floatValue];
int trackShowColum = [trackShow.text floatValue];
int trackTotalColum= [trackTotal.text intValue];
int trackWinTotal = trackWinColum * 1;
NSLog(#"%d", trackWinTotal);
int trackPlaceTotal = trackPlaceColum *.5;
NSLog(#"%d", trackPlaceTotal);
int trackShowTotal= trackShowColum *.25;
NSLog(#"%d", trackShowTotal);
float totalOfTrackColums = trackWinTotal + trackPlaceTotal + trackShowTotal;
float totalTrackAllTogether= (float) totalOfTrackColums / trackTotalColum;
onOffLabel.text = [[NSString alloc] initWithFormat:#"%f", totalTrackAllTogether];
}
I seem to be held up when trying to multiply floating points with whole numbers, and displaying it through onOffLabel.text. Thank you for the help!

These is basic stuff which works the same in C, C++ and Objective-C. If you do a floating-point calculation and store the result in an int, everything after the decimal point is dropped.
Furthermore, by using float instead of double you get massive rounding errors without any benefit. Instead of
int trackPlaceColum = [trackPlace.text floatValue];
write own of these:
NSInteger trackPlaceColumn = [trackPlace.text integerValue];
double trackPlaceColumn = [trackPlace.text doubleValue];
BTW. It's a column, not a colum. And you will get a crash if you divide by zero. So check whether trackTotalColumn is zero or not in your code.

Related

Dynamic values in percentage format in Objective C

I want to know making Objective C variable values in percentage format. I am getting 6 values dynamically. Sometimes values might increase more than 100. For ex: Avalue=143, Bvalue=450, Cvalue=76, Dvalue=98, Evalue=123, Fvalue=56
how can i format each value under percentage format?
(Avalue * 100)/100.f
(Bvalue * 100)/100.f
(Cvalue * 100)/100.f
(Dvalue * 100)/100.f
(Evalue * 100)/100.f
(Fvalue * 100)/100.f
Is this proper way of doing it?
Well, percentage numbers are in essence fractions. In mathematics, a percentage is a number or ratio expressed as a fraction of 100.
if you want to compare numbers like in your case, compare each numbers to the sum oaf all value, then set the sum as 100%.
float sumAllValues = (Avalue + Bvalue + ...);
float aValuePercent = (Avalue / sumAllValues) * 100.f
you can format that percentage number with NSNumberFormatter
NSString *result1 = [NSNumberFormatter localizedStringFromNumber:[NSNumber numberWithFloat:aValuePercent];
numberStyle:NSNumberFormatterPercentStyle];
btw: why the variables begin with a Uppercase?
-Edit-
When you divide integers, keep in mind that integers divided by integer results integer.
I wrote a short example for the console.
NSInteger a = 5;
NSInteger b = 6;
NSInteger c = a * 100 / b;
NSInteger d = a / b * 100;
// example with conversion al values to float
float e = [[NSNumber numberWithInteger:a] floatValue] / [[NSNumber numberWithInteger:b] floatValue] * 100;
NSLog(#"resulting int c: %lu", c);
NSLog(#"resulting int d: %lu", d);
NSLog(#"resulting float e: %f", e);
2017-02-14 19:36:54.897 IntegerTest[2291:1238166] resulting int c: 83
2017-02-14 19:36:54.898 IntegerTest[2291:1238166] resulting int d: 0
2017-02-14 19:36:54.898 IntegerTest[2291:1238166] resulting float e: 83.333328
Program ended with exit code: 0
You see, when you multiply the first integer with 100 and the divide, you get 83.
The other way round (what is mathematically correct), first the division and after the multiply, you get 0, because 5/6 is less than 1 and the integer value is set to 0. Since multiplying 0 by any other value remains 0, the result is 0.
EDIT AGAIN -
the code from console is written with plain integers, but in essence they are the same as your values. First the multiplication, then the division.
NSInteger aPercentage = (Avalue * 100) / Bvalue;
or cast all values to floats. like so:
float aValueFloat = [[NSNumber numberWithInt:Avalue] floatValue];
EDIT AGAIN -
This was only for example reasons. Value is only the divisor because I do not know, to wash value you want to compare those values. In this example Avalue is compared to Bvalue, say Avalue is percent from Bvalue.
If you only want to print out Avlue = 143 in 143% then:
NSInteger aValue = 146;
NSString *aValuePercentString = [NSString stringWithFormat:#"%ld%%", aValue];
NSLog(#"%#", aValuePercentString);
Output: 2017-02-15 16:52:26.346 test[2132:1070601] 146%
Note1: This works with values as Integers. If the values are NSNumbers use %# instead of %ld.
Note2: Value is not an Integer anymore but a string.
Hope it helps!

Formatting an integer value

Im obtaining an int value from UITextField [self.dbRef.text intValue];
I want to then format that value so I can add a decimal place that precceds the number ie. If [self.dbRef.text intValue]; returns 4 i need that value to be 0.04
So far I have tried various ways including
float Y = ([self.dbRef.text intValue]/100);
slice.value = Y;
NSLog(#"float Y value = %f",Y);
returns zero
NSString* formatedTotalApplianceString = [NSString stringWithFormat:#"0.%#", self.dbRef.text];
NSLog(#"formated string = %#",formatedTotalApplianceString);
int totalAppliances = [formatedTotalApplianceString intValue];
NSLog(#"Resulting int value = %d",[formatedTotalApplianceString intValue]);
slice.value = totalAppliances;
NSLog(#"total appliances int value = %d",totalAppliances);
returns zero
You're doing an integer division, so the 0 value is correct in that context as integers cannot represent fractions (unless you're doing fixed point arithmetics, but that's a different can of worms). You need to do a floating point division, for example:
float Y = ([self.dbRef.text floatValue]/100.0f);
Either the [self.dbRef.text floatValue] or the 100.0f will turn this into a float division, because if the other side would be an int it would automatically get casted to a float. But the "best" way is to have both values of the same type.
Change
float Y = [self.dbRef.text intValue]/100;
to
float Y = ((float)[self.dbRef.text intValue])/100;
in your first variant.
Dividing int by int returns you int result even if then you assign it to float. 4/100 = 0 in such case.
The problem with [self.dbRef.text intValue]/100 is that it's an integer division. It drops the fraction. One way to work around it is to divide by 100.0:
[self.dbRef.text intValue]/100.0
However, this is not the most efficient way of doing it if all you need is adding a zero in front of a fraction: you could avoid float altogether by padding your printed int to two positions with leading zeros:
// If text is 4, the code below prints 0.04
NSLog(#"0.%02d", [self.dbRef.text intValue]);
The first code returns zero because you are performing an integer division, which produces an integer result. You should cast the value to a float.
The second code also returns zero because you're asking for the intValue of a floating point value. So the decimal part will be discarded.
NSString has also a floatValue method, you should use it to get a floating value. Once divided by 100 you will still have a floating point value (in a division if the quotient or the dividend is a float and the other an integer, the integer gets promoted to float):
float Y = ([self.dbRef.text floatValue]/100);
slice.value = Y;

Adding fractions calculation not working in IOS

I am trying to add fractions to get a value to put in for my progress bar but am just getting 0. here is what I have and what it is logging.
NSLog(#"prog::%f",self.progView.progress);
int total = self.forms.count;
float calc = (float)(self.progView.progress / total) + (1/total);
NSLog(#"calc::%f",calc);
NSLog(#"total::%d",total);
self.progView.progress = calc;
NSLog(#"prog now:%f", self.progView.progress);
Log:
prog::0.000000
calc::0.000000
total::4
prog now:0.000000
Take care of where you place your cast to float. Try changing from this:
float calc = (float)(self.progView.progress / total) + (1/total);
To this:
float calc = ((float)self.progView.progress / (float)total) + (1/(float)total);
Alternatively, make total a float rather than an int, e.g.
float total = self.forms.count;
float calc = ((float)self.progView.progress / total) + (1 / total);

Division in iOS Xcode

Not terribly familiar with Xcode or Objective-C but trying to learn. Hopefully someone can help me out with a problem I'm having.
I have two fields, one called price and one called units and I'm trying divide the inputs of the cells by each other and then display the result with the correct currency of the 'nationality' of the device when a button is pressed.
So far I have of the action of the button I have;
- (IBAction)calculate:(id)sender {
int x = [price.text floatValue];
int y = [units.text floatValue];
int calc_result = x / y;
self.result.text = [NSString stringWithFormat:#"%.2f", calc_result];
}
which outputs a result into a label field WITHOUT the decimal remainder.
How can I get it to display the decimal remainder to 2 decimal places and put in front the currency found from the 'nationality' of the device.
Thanks in advance!
You are using an integer here:
int x = [price.text floatValue];
int y = [units.text floatValue];
int calc_result = x / y;
You should use a floating point number:
float x = [price.text floatValue];
float y = [units.text floatValue];
float calc_result = x / y;

Objective-C Random Numbers

I'm making a simple pong game. To make the ball move at the beginning of a new round, I am using
ballVelocity = CGPointMake(4 - arc4random() % 8,4 - arc4random() % 8);
However, the important part is just this:
4 - arc4random() % 8
However, there are a few problems with this: first and foremost, it doesn't really generate a random number. Only after I quit the simulator, then reopen it are new numbers generated. Secondly, I only want it to generate numbers between -4 and -2 or 2 and 4.
arc4random() is the preferred random function on the iphone, instead of rand(). arc4random() does not need seeding.
This code will generate the ranges you're interested in:
int minus2_to_minus4 = (arc4random() % 3) - 4;
int two_to_four = (arc4random() % 3) + 2;
You need to look at the rand() function. Basically, you "seed" it with a start value, and it returns a new random number every time you call it.
Or look at this question which has a full example using arc4random.
This will give you a floating point number between -4 and -2 OR 2 and 4
float low_bound = -4; //OR 2
float high_bound = -2;//OR 4
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
If you want a number in -4…-2 AND 2…4 try this:
float low_bound = 2;
float high_bound = 4;
float rndValueTemp = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
float rndValue = ((float)arc4random()/0x100000000)<0.5?-rndValueTemp:rndValueTemp;

Resources