Reputation: 359
Sorry for not posting any code. This question relates to division and multiplication by floating point numbers when working in xcode ios.
I have variable which i need to be divided by 2.055926336e+09. But unfortunately compiler does not divide it?
How i use it in the code
float variable1=((variable2)/(2.055926336e+09));
This is true for dividing with smaller values (Eg: - (1/(2.055926336e+09) ) What is the reason for this? Any efficient method to get this done?
Thanks in advance!
Upvotes: 0
Views: 1579
Reputation: 2703
@rob mayoff's answer is quite valid, but you might not be interested in showing the scientific result to the user. My take on that is to break the large number into two strings and concat them like below
-(NSString*) stringWithLargeNumber:(double)large
{
int fraction1 = large/10000;
float fraction2 = large-fraction1;
return [NSString stringWithFormat:@"%d%.2f", fraction1, fraction2];
}
Hope this helps
Upvotes: 0
Reputation: 4373
When you say "it does not divide", do you mean that the result it returns is 0
?
If so, your problem is floating point precision. 10 / 2055926336
is an INCREDIBLY small number. Floats only have 6 decimal places of precision, and aren't going to be able to store this accurately.
Your problem is not that the numbers are too large, but that the result is far too small. Try using the double
data type instead, but keep in mind that if your numbers get even smaller than this, it won't work (doubles have 15 digits of precision).
Upvotes: 1
Reputation: 385998
I suspect the problem isn't in your computation. It's in your printing. You're probably trying to print the answer using a format like %f
. By default, %f
prints 6 digits to the right of the decimal point.
The value of 10/2.055926336e+09 is 0.000000004863987500377056... which, as you can see, has more than 6 zeroes immediately following the decimal point. If you try to format it using %f
, you'll just get zero.
If you format it with %e
(or %g
) instead, the formatter will use scientific notation, and print the result as 4.863988e-10
, showing that the result is not zero.
Upvotes: 7