Quote:
Originally Posted by Objective Zero
Hey,
I found the following method on the web but I do not want all these decimals places. I only want things like 5.2 or 7.4 etc...
How would I adjust this method to do that?
Code:
-(float)randomFloatBetween:(float)num1 andLargerFloat:(float)num2
{
int startVal = num1*10000;
int endVal = num2*10000;
int randomValue = startVal + (arc4random() % (endVal - startVal));
float a = randomValue;
return (a / 10000.0);
}
|
Because of the way computers represent floating point numbers in binary, a decimal number doesn't really have "a number of decimal places." The number is stored internally as a sum of fractions of powers of 2.
0.1, for example, is roughly 1/16+1/32+1/256+1/512+1/4096 (plus some even smaller fractions.)
If you use code like this
float num = 1.1
NSLog(@"num = %.9f", num);
You will get something like
"num = 1.099999999997"
If you want to display a number to a smaller number of decimal places, use string formatting to do it. Like:
NSString* numString = [NSString stringWithFormat:@"%.1f", num];
That will give you a string like 5.2 or 7.4 as you want.