How to convert a double to NSInteger? - iphone

Very simple question here. I have a double that I wish to convert back to a NSInteger, truncating to the units place. How would I do that?

Truncation is an implicit conversion:
NSInteger theInteger = theDouble;
That's assuming you're not checking the value is within NSInteger's range. If you want to do that, you'll have to add some branching:
NSInteger theInteger = 0;
if (theDouble > NSIntegerMax) {
// ...
} else if (theDouble < NSIntegerMin) {
// ...
} else {
theInteger = theDouble;
}

NSInteger is a typedef for a C type. So you can just do:
double originalNumber;
NSInteger integerNumber = (NSInteger)originalNumber;
Which, per the C spec, will truncate originalNumber.

but anyway, assuming you want no rounding, i believe this should work simply
double myDouble = 10.4223;
NSInteger myInt = myDouble;
edit for rounding: (i'm sure theres a much simpler (and precise) way to do this.. (this also doesn't account for negative numbers or maximum boundaries)
double myDecimal = myDouble - myInt;
if(myDecimal < 0.50)
{
//do nothing
}
else
{
myInt = myInt + 1;
}

NSInteger is a typedef, it's the same as using an int. Just assign the value like:
double d;
NSInteger i = d;

JesseNaugher mentions rounding and I note the OP needs were met with a simple truncate, but in the spirit of full generalisation it's worth remembering the simple trick of adding 0.5 to the double before invoking floor() to achieve rounding. Extending Jonathan Grynspan's comment: NSInteger myInt = floor(myDouble + 0.5); i.e., rounding up in absolute terms. If rounding 'up' means rounding away from zero a more convoluted approach is needed: NSInteger myInt = floor( myDouble + (myDouble < 0.0 ? -0.5 : 0.5) );

Related

Divide NSInteger with int

I am trying to divide NSInteger with some number, but I am receiving errors.
This is what I am trying to do:
length = [corner count];
for (int i=0; i<length; i++) {
if ([resultDate rangeOfString:[corner objectAtIndex:i]].location != NSNotFound) {
cornerResult++;
}
}
cornerResultLabel.text = [NSString stringWithFormat:#"%i", cornerResult];
This works as it should.. I search through the array and count the results and write it.
But, I need cornerResult divided with 4. When I add cornerResult / 4 it shows me the error(as I wrote in comment). I have no idea why is this making problem.
you probably meant to divide the intValue of the NSNumber, not the NSNumber* itself:
int num = number.intValue;
int result = num / 4;
(full code sample and error message would help)
You are dividing an int which becomes a float , use %f instead.
I fix it this way. First I defined int and after that I set NSInteger value to int and after that divide.
int helper = cornerResult;
helper = helper / 4;

Implementing decimal instead of fraction, Calculator Xcode App

Ive scoured everywhere and haven't found a situation similar to mine.. New to Xcode/Objective C, I am putting together a dual purpose (fraction/decimal) calculator app. Ive found some good stuff on the fractions, and have them calculating correctly. However the decimal is a different story. I can get it to appear with this:
-(IBAction) pressDecimal
{
NSRange range = [display.text rangeOfString:#"."];
if ( range.location == NSNotFound ) {
display.text = [display.text stringByAppendingString:#"."];
}
or this:
-(IBAction) pressDecimal
{
[displayString appendString: #"."];
display.text = displayString;
}
The latter works great, to DISPLAY it on the calculator. I try to read it in as a slot, a double, and i just can't seem to read it in properly... here is how i get the digits in:
- (void) workNums: (int) nums
{
currentNumber = currentNumber * 10 + nums;
[displayString appendString:
[NSString stringWithFormat: #"%i", nums]];
display.text = displayString;
}
//uses tags from attribute inspector (decimal tagged 10)
-(IBAction)pressNum:(UIButton *)sendIT
{
int nums = sendIT.tag;
[self workNums: nums];
}
Ive looked everywhere, tried changing from floats to doubles ( i can get it to display 0.00's when i play with them) also here is my method to converting the ANSWER that is a FRACTION to a DECIMAL..which works great too:
- (double) convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
else
return NAN;
So again, cleanly stated... How may I get Objective C to see the decimal inputed in the app, and display the answer as a decimal properly.. am i screwed because i started this a mainly a fraction calculator? Thanks from a noob that moved from BASIC to Objective C
EDIT 4/27/12 ***
(new to Stack - but please read my comment below.. i am looking to find out why i can't read decimals into my program... I've tried changing from ints (which i know won't work) and doubles and floats, but all i get is 0.00 on user input when running this all as doubles:
-(IBAction)pressNum:(UIButton *)sendIT
{
int nums = sendIT.tag;
[self workNums: nums];
}
- (void) workNums: (int) nums
{
currentNumber = currentNumber * 10 + nums;
[displayString appendString:
[NSString stringWithFormat: #"%i", nums]];
display.text = displayString;
}
So the goal is to be able to CALCULATE a user inputted decimal number...any suggestions on a if/else situation as these numbers build up in an accumulator / and a double for currentNumber and get turned into numerators/denominators later down the line..(which is probably my issue, but it shouldn't be hard, but I'm making it hard, to use a BOOL or something to say, hey..this isn't a fraction, its a decimal - so lets do this - PLEASE HELP!! GOING NUTS!
I may be thinking this is much simpler than it is, but: if you already have a string like #"3.14" in displayString then you can convert that directly to a double:
double doubleValue = [displayString doubleValue];
Would that not be enough to get the double value and perform calculations?

Percentage Calculation always returns 0

I am trying to calculate the percentage of something.
It's simple maths. Here is the code.
float percentComplete = 0;
if (todaysCollection>0) {
percentComplete = ((float)todaysCollection/(float)totalCollectionAvailable)*100;
}
Here the value of todaysCollection is 1751 and totalCollectionAvailable is 4000. Both are int.
But percentComplete always shows 0. Why is this happening? Can any one Help me out.
I'm new to Objective C.
But percentComplete always shows 0
How are you displaying percentComplete? Bear in mind it's a float - if you interpret it as an int without casting it you'll get the wrong output. For example, this:
int x = 1750;
int y = 4000;
float result = 0;
if ( x > 0 ) {
result = ((float)x/(float)y)*100;
}
NSLog(#"[SW] %0.1f", result); // interpret as a float - correct
NSLog(#"[SW] %i", result); // interpret as an int without casting - WRONG!
NSLog(#"[SW] %i", (int)result); // interpret as an int with casting - correct
Outputs this:
2010-09-04 09:41:14.966 Test[6619:207] [SW] 43.8
2010-09-04 09:41:14.967 Test[6619:207] [SW] 0
2010-09-04 09:41:14.967 Test[6619:207] [SW] 43
Bear in mind that casting a floating point value to an integer type just discards the stuff after the decimal point - so in my example 43.8 renders as 43. To round the floating point value to the nearest integer use one of the rounding functions from math.h, e.g.:
#import <math.h>
... rest of code here
NSLog(#"[SW] %i", (int)round(result)); // now prints 44
Maybe try with *(float)100, sometimes that is the problem ;)
I think that your value for todaysCollection and totalCollectionAvailable is wrong. Double check for that.
Put the NSLog(#"%d", todaysCollection) right before the if statement

Do I need to use decimal places when using floats? Is the "f" suffix necessary?

I've seen several examples in books and around the web where they sometimes use decimal places when declaring float values even if they are whole numbers, and sometimes using an "f" suffix. Is this necessary?
For example:
[UIColor colorWithRed:0.8 green:0.914 blue:0.9 alpha:1.00];
How is this different from:
[UIColor colorWithRed:0.8f green:0.914f blue:0.9f alpha:1.00f];
Does the trailing "f" mean anything special?
Getting rid of the trailing zeros for the alpha value works too, so it becomes:
[UIColor colorWithRed:0.8 green:0.914 blue:0.9 alpha:1];
So are the decimal zeros just there to remind myself and others that the value is a float?
Just one of those things that has puzzled me so any clarification is welcome :)
Decimal literals are treated as double by default. Using 1.0f tells the compiler to use a float (which is smaller than double) instead. In most cases it doesn't really matterĀ if a number is a double or a float, the compiler will make sure you get the right format for the job in the end. In high-performance code you may want to be explicit, but I'd suggest benchmarking it yourself.
As John said numbers with a decimal place default to double. TomTom is wrong.
I was curious to know if the compiler would just optimize the double to a const float (which I assumed would happen)... turns out it doesn't and the idea of the speed increase is actually legit... depending on how much you use it. In math-heavy application, you probably do want to use this trick.
It must be the case that it is taking the stored float variable, casting it to a double, performing the math against the double (the number without the f), then casting it back to a float to store it again. That would explain the diference in calculation even though we're storing in floats each time.
The code & raw results:
https://gist.github.com/1880400
Pulled out relevant benchmark on an iPad 1 in Debug profile (Release resulted in even more of a performance increase by using the f notation):
------------ 10000000 total loops
timeWithDoubles: 1.33593 sec
timeWithFloats: 0.80924 sec
Float speed up: 1.65x
Difference in calculation: -0.000038
Code:
int main (int argc, const char * argv[]) {
for (unsigned int magnitude = 100; magnitude < INT_MAX; magnitude *= 10) {
runTest(magnitude);
}
return 0;
}
void runTest(int numIterations) {
NSTimeInterval startTime = CFAbsoluteTimeGetCurrent();
float d = 1.2f;
for (int i = 0; i < numIterations; i++) {
d += 1.8368383;
d *= 0.976;
}
NSTimeInterval timeWithDoubles = CFAbsoluteTimeGetCurrent() - startTime;
startTime = CFAbsoluteTimeGetCurrent();
float f = 1.2f;
for (int i = 0; i < numIterations; i++) {
f += 1.8368383f;
f *= 0.976f;
}
NSTimeInterval timeWithFloats = CFAbsoluteTimeGetCurrent() - startTime;
printf("\n------------ %d total loops\n", numIterations);
printf("timeWithDoubles: %2.5f sec\n", timeWithDoubles);
printf("timeWithFloats: %2.5f sec\n", timeWithFloats);
printf("Float speed up: %2.2fx\n", timeWithDoubles / timeWithFloats);
printf("Difference in calculation: %f\n", d - f);
}
Trailing f: this is a float.
Trailing f + "." - redundant.
That simple.
8f is 8 as a float.
8.0 is 8 as a float.
8 is 8 as integer.
8.0f is 8 as a float.
Mostly the "f" can be style - to make sure it is a float, not a double.

Find the smallest value among variables?

I have from 4 up to 20 variables that differ in size.
They are all of type float and number values.
Is there an easy way to find the smallest value among them and assign it to a variable?
Thanks
Not sure about objective-c but the procedure's something like:
float min = arrayofvalues[0];
foreach( float value in arrayofvalues)
{
if(value < min)
min=value;
}
I agree with Davy8 - you could try rewriting his code into Objective C.
But, I have found some min()-like code - in Objective C!
Look at this:
- (int) smallestOf: (int) a andOf: (int) b andOf: (int) c
{
int min = a;
if ( b < min )
min = b;
if( c < min )
min = c;
return min;
}
This code assumes it'll always compare only three variables, but I guess that's something you can deal with ;)
The best solution, without foreach.
`- (float)minFromArray:(float *)array size:(int)arrSize
{
float min;
int i;
min = array[0]
for(i=1;i<arrSize;i++)
if(array[i] < min)
min = array[i];
return min;
}
`
If you want to be sure, add a check of the arrSize > 0.
Marco
Thanks for all your answers and comments.. I learn a lot from you guys :)
I ended up using something like Martin suggested.
if (segmentValueNumber == 11){
float min = 100000000;
if(game51 > 0, game51 < min){
min=game51;
}
if(game52 > 0, game52 < min){
min=game52;
}
}
...............................................
I could not figure out how to implement it all into one array since each result depends on a segment control, and I think the program is more optimised this way since it only checks relevant variables.
But thanks again, you are most helpful..