I need to show exact decimal points.
float value =26/5;
When i logged value it shows 5.00000 i need it as 5.2 exactly. I have also used double value nothing helps.
I need to show exact decimal points.
float value =26/5;
When i logged value it shows 5.00000 i need it as 5.2 exactly. I have also used double value nothing helps.
float value = 26.0 / 5.0;
will do. In your code, the numbers are treated as integers so the division supplies an integer result.
In float value = 26/5;
both the numerator and denominator are integers so integer math will be used and integer math produces an integer by rounding down which is then converted to a floating point number.
Make one or both floating point values and you will get a floating point result:
float value = 26/5.0;
or
float value = 26.0/5;
or
float value = 26.0/5.0;
or you can use casting instead of changing the numbers floating point:
float value = (float)26/(float)5;
Note that 26.0/5.0 does not produce exactly 5.2 because 5.2 can not be exactly represented in floating point, the value will be something similar to 5.19999980926513671875. This may present problems.
Example:
float value = 26.0/5.0;
NSLog(@"value: %.20f", value);
Output:
value: 5.19999980926513671875
While a lower precision display will look correct:
NSLog(@"value: %f", value);
Output:
value: 5.200000
If you want to only display two decimal points:
NSLog(@"value: %.2f", value);
Output:
value: 5.20
Simply add .0 after the numbers as
float value =26.0/5.0;
which will work as float, without .0 they are treated as integers.
When you need to log it or print it, use this: [[NSNumber numberWithFloat:someFloatValue] stringValue];
As user "return true" said, the value is exact, but if you want exact decimals to be printed or logged as string, you can use the above code.
And don't forget to use 26.0 / 5.0 so you get a decimal.