Reputation: 65
I am having an issue with using a float in a UILabel.
float doubleNum;
floatNum = 10 / 20;
cashLabel.text = [[NSString alloc] initWithFormat:@"%f", floatNum];
If I use "floatNum = 10 / 10;" it correctly returns "1.000000000", however, if I put in "floatNum = 10 / 20" it returns "0.0000000". I have tried about everything I know and it does not work. I know it's a dumb mistake, but I can't figure it out.
Happy Holidays. :)
Upvotes: 2
Views: 2788
Reputation: 2421
You need to cast one of the integer's to a float.
Try replacing the divisional line with:
float floatNum = (float) 10 / 20;
and you should get the correct answer.
Or if possible just use floats in your division:
float floatNum = 10.0f / 20.0f;
should also work
Upvotes: 4
Reputation: 21
The issue here is that you are assigning floatNum the result of dividing one INTEGER by another. The result of 10 / 20 is indeed 0 and as a float, it appears as 0.0000000. In order to obtain a proper result, you need to either use a cast type to turn it into a float or add a .0 to one of the numbers. In division, if one of the numbers is a float (which is easily done by just adding a .0 to one of them), the result will be a float as well.
Upvotes: 2
Reputation: 6401
Consider following example to understand how floats work:
float a = 1/120;
float b = 1.0/120;
float c = 1.0/120.0;
float d = 1.0f/120.0f;
NSLog(@"Value of A:%f B:%f C:%f D:%f",a,b,c,d);
Output: Value of A:0.000000 B:0.008333 C:0.008333 D:0.008333
For float variable a : int / int yields integer which you are assigning to float and printing it so 0.0000000
For float variable b: float / int yields float, assigning to float and printing it 0.008333
For float variable c: float / float yields float, so 0.008333
Last one is more precise float. Previous ones are of type double: all floating point values are stored as double data types unless the value is followed by an 'f' to specifically specify a float rather than as a double.
Change your code to:
float floatNum;
floatNum = 10.0f / 20.0f;
cashLabel.text = [[NSString alloc] initWithFormat:@"%f", floatNum];
Upvotes: 0
Reputation: 2227
try floatNum = 10.0f/20.0f
(i.e. make sure the calculation is being done with floats rather than ints)
Upvotes: 0
Reputation: 3634
Normally, C performs "integer division" (basically, division without the remainder -- 10/3 is 3R1, so it yields 3).
When you type floatNum = 10/20
, it does 10/20 = 0
(remainder 10).
To fix this, you have to tell the program that you're giving it floating point numbers. Try using:
floatNum = 10.0 / 20
,
floatNum = 10 / 20.0
, or
floatNum = float (10 / 20)
.
All of those should work.
Upvotes: 0