Divide Long Long Number as Percent - iphone

In an iphone app, I have 2 large numbers stored in NSStrings, and I want to figure out the float number that is achieved by dividing them.
Right now, I have:
unsigned long long number = [string1 longLongValue];
unsigned long long number2 = [string2 longLongValue];
float percent = number/number2;
[textField setText:[NSString stringWithFormat: #"%f%%",percent]];
(I assume I have to use "unsigned long long" instead of ints because the numbers in the NSStrings are pretty high- the first one is 309,681,754 and the second is 6,854,433,820)
However, after I do this, I always get 0% in the text field. What am I doing wrong?
Thanks for any help in advance.

You are dividing integers. That always results in an integer.
What you need to do is to cast them to floats before dividing. This should work:
float percent = (float)number / (float)number2;

Related

Concatenating Two Integers [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
It might be the simplest Question, but at this time ,I am not getting any Idea on how to implement this.
Ok, The problem is of how to concatenate two integers.
For Eg: I want to create an integer say 0000 using two different integers 00 and 00. I tried using NSString , but I failed.
My Code is :
int num1 = 00;
int num2 = 00;
NSString *str = [NSString stringWithFormat:#"%d%d",num1,num2];
int num = [str intValue];
NSLog(#"num = %d",num); // It Logs 0 but I want 0000.
Does anyone have better Idea ?
EDIT :
Please Note that , I want to use that num to set the tag of textfield. That's why all the zeros are essential. So my main Problem starts here.
I have one tableview which contains custom cells. This custom cell has more than 10 textfields. Now I want to uniquely identify all the textfields for editing. That's why the tag for that textfield must be the integer concatenated by two values called rowNumber and textFieldNumber (means which textField out of 10.).
So my question is what I am trying to do is right or not ? And if not then give me some useful solution.
The integer data types (such as int) only store the integer value, not formatting information. Therefore you lose the number of leading zeroes (which do not affect the integer value, i.e., 0, 00, and 0000 are the same integer: zero).
If you wish to retain formatting information, you must store it separately. A simple way is to just store the string itself. Or, if you always want to have the same number of digits, then alter the formatting string:
int num1 = 0;
int num2 = 0;
NSString *str = [NSString stringWithFormat:#"%02d%02d",num1,num2];
After the above code, str will be "0000". However, converting it to int and then logging with %d formatting results in 0 once more (since 0000 and 0 are the same integer).
Edit: For the purpose of generating unique integers for tagging purposes, given a row number (rowNumber) and text field number (textFieldNumber), use a formula like:
tagNumber = rowNumber * 100 + textFieldNumber;
This way the text fields of row 0 will have numbers 0..99, those on row 1 will have 100..199, etc. If more than 100 text fields are required per row, simply multiply by a larger number, like 1000.
In integer arithmetic these values can be converted back to row and field numbers with:
rowNumber = tagNumber / 100;
textFieldNumber = tagNumber % 100;
Try to use this:
int num1 = 0;
int num2 = 0;
int num3=0;
int num4=0;
NSString *str = [NSString stringWithFormat:#"%d%d%d%d",num1,num2,num2,num3];
int num = [str intValue];
NSLog(#"num = %0*d",str.length,num);
Hope this helps you.
but dont init as like this "int num1=00" because it init "0" only in num1.
Why turn it back into an int? You should print the string you just formatted:
NSLog(#"num = %#",str);
As numbers, there is no difference between 0 and 0000. Integers only preserve the value, not the formatting (that's what strings are for).
Multiply the first integer with 100 and add the second integer to it. You should be able to print it using:
NSLog([NSString stringWithFormat:#"%04d", sum]);
which will put leading zeros.
You can pad it as :
NOTE: both the num1 and num2 must be of 2 digits. If its size increases then it wont work.
int num1 = 00;
int num2 = 00;
NSString *str = [NSString stringWithFormat:#"%d%d",num1,num2];
int num = [str intValue];
NSLog(#"num = %04d",num);
If printing is not the real issue then i guess you need a multiplication factor to set the tag
let it be 10000 and add it to some sequence no to get the unique tag value.
or you can use num as string and multiply by 10 in for loop for num.length times

double from fraction string iPhone

I have an array of strings that are fractions (1/3, 2/5) etc. I need to take these strings and use them as doubles for calculations. The fractions go into the arrays as strings. Why isn't the below code working?
NSString *localString = [array objectAtIndex:1];
double NewDouble = [localString doubleValue];
I get the first int in each string (1 instead of .333 & 2 instead of .4 from above).
I'm missing something easy and it's driving me crazy.
Thanks
You cannot take a NSStringrepresenting a fraction and demand its doubleValue. You have to split the string and calculate the fraction manually.

doubleValue does not convert the object to a double value correctly at all times

I have an NSArray in which I would like to store double values. I defined it as follow
NSMutableArray *setOfDoubles;
I add the elements as follow
NSNumber *num;
num = [NSNumber numberWithDouble:someDouble];
[setOfDoubles addObject:num];
And I read the element as follow
num = [setOfDoubles lastObject];
[setOfDoubles removeLastObject];
doubleValueToUse = [num doubleValue];
My problem is sometimes (Not always), for example when num (as an object) is 5.1, doubleValueToUse (as a double value) is 5.099999999999996. The way I figured num (as an object) is 5.1 is that I debug and when I am hovering the mouse on top of num on the line num = [setOfDoubles lastObject]; it shows 5.1 but after doubleValue conversion it becomes the number I mentioned. Does anybody know why is this happening?
Not every number can be accurately represented using a float variable. For example, you can't precisely represent, say, 1/3 using a finite number of digits in our common decimal (base-10) system, but in ternary (base-3), it would be just 0.1. Similarly, the numbers you can write with a finite number of digits in decimal, may not necessarily have the finite number of digits in their binary representation, hence the error.
A few links on the topic if you are interested:
http://floating-point-gui.de/basic/
http://www.mathworks.com/support/tech-notes/1100/1108.html
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html
This is normal for float values.
If you want to save initial (same) representation of float numbers in all places of your code, you can save them, for example, in NSString. When you will need float number you will just write [NSString floatValue];. But it is not effective if you have large amount of float values.

Different results for the same function

Can someone clarify to me please why past2 is NOT negative when this code is run? Even though past is.
Thanks.
NSTimeInterval p1 = (arc4random()%600000);
NSTimeInterval past = -p1;
NSTimeInterval past2 = -(arc4random()%600000);
arc4random() returns an unsigned int (u_int32_t), so trying to make it negative is coercing the result to unsigned as well, which is why you're getting a very large positive number instead of a negative number.
If you want to get a negative random result in one call, try:
NSTimeInterval past2 = - (int) (arc4random()%600000);
joe

Proper Usage and Formatting of a Float in Objective-C (or C)

I have an iPhone app. I am storing a float value, (distance), in my sqlite3 db. (The field in the db is formatted to float) I am able to store float values correctly in the db no problem. However, I can't seem to figure out how to pull the value back out of the db the format and present it correctly. Here is my code for pulling the value out of my db and using it:
NSString *itemDistance = [NSString stringWithFormat:#"%f",[item distance]];
float questionDistance = [itemDistance floatValue];
[item distance] is a float value. I can't get this to work. I get a REALLY long value instead. What am I doing wrong? Any help would be greatly appreciated.
Thank you in advance for your help,
L.
Assuming your -distance method is returning the right value, then this sounds like basic misunderstanding of how floats work in C. Common mistake. Every developer falls into this trap at least once.
Floating point numbers can actually only represent a fairly limited number of values. Specifically, unless you happen to choose a value that is exactly representable as a float, you'll get the nearest value, which will often have many decimal places of data.
The reason for this is because a float is only 32 bits; 4 bytes. Now, how many numbers with decimal points are there between 0..1000000 or 0..1000 or, even, 0..1. Infinite. Floats implement a very finite subset of possible numeric values and do so in a way where the resulting possible values may have many decimal places.
Consider:
printf("%5.18f\n", (float) 2.05);
printf("%5.18f\n", (float) 2.45);
printf("%5.18f\n", (float) 4200.75);
printf("%5.18f\n", (float) 37.89);
printf("%5.18f\n", (float) 1.2);
printf("%5.18f\n", (float) -1.2);
This prints:
2.049999952316284180
2.450000047683715820
4200.750000000000000000
37.889999389648437500
1.200000047683715820
-1.200000047683715820
Those values are as close to the values in the bit of code that a float could represent.
If you need more precision, use a double. More precision than that? Use NSDecimalNumber.
And, if you can, use CoreData. It makes managing this kind of thing a bit more straightforward.
why go round in circles?
NSString *itemDistance = [NSString stringWithFormat:#"%.2f",[item distance]];
float questionDistance = [itemDistance floatValue];
Where the .2 is saying I want 2 decimal places.
Whats the type of of distance? If it is an instance of NSNumber then I dont think the code you wrote will work, try
NSString *itemDistance = [[item distance] stringValue];
float questionDistance = [itemDistance floatValue];
or even
float q=[[item distance] floatValue];