Below is the solution code for an excercise from KN King\'s Modern Programming approach.
#include
int main(void)
{
int i;
float j,x;
A double is not infinitely accurate, and it does not store numbers in decimal, so it cannot precisely store 0.085. If you want to print a number to two significant figures, use the precision format specifier - see http://www.cprogramming.com/tutorial/printf-format-strings.html for examples.
double value = 0.085;
NSLog(@"%.2g", value);
This will print "0.085"
Be aware that using the precision specifier normally controls the number of digits displayed after the decimal point - but in the case of a double, it controls significant figures.
float value = 0.085;
NSLog(@"%.2f", value);
Will print "0.09"
The floating-point formats record only a mathematical value. They do not record how much precision the value had when scanned (or otherwise obtained). (For that matter, this is true of the integer formats too.)
When you display a floating-point value, you must specify how many digits to display. The C standard defines a default of six digits for the %f
specifier:1
A double argument representing a floating-point number is converted to decimal notation in the style [−]ffffd.ffffd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is zero and the # flag is not specified, no decimal-point character appears. If a decimal-point character appears, at least one digit appears before it. The value is rounded to the appropriate number of digits.
You specify the precision by writing the number of digits after a period in the format specifications, such as %.2f
:2
The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; if only the period is specified, the precision is taken as zero.
(The asterisk is used to specify the number of digits in a int
parameter passed to printf
.)
Notes
1 C 2011 (N1570) 7.21.6.1 8.
2 C 2011 (N1570) 7.21.6.1 4.
Why are there extra decimal values seen for floats?
That's why floats are floats.By default %f lets you display 6 digits after decimal. That's nothing do do with the precision of the number stored.Numbers are stored according to the IEEE 754 FLOATING POINT representation in most systems.And numbers are not stored with decimal points. So, since you do not control how you store numbers, you can't change the precision.Precision is fixed.
Is there any default precision set for float and how can I change it.
Again , precision is not default its not how it is stored. Check its representation for 32 bit or 64 bit.Youwould like to print more/less digits after decimal.You can do this :
float i=2.89674534423;
printf("%.10f",i); Prints 10 digits after decimal.
You can't change the precision of a float, but (as it sounds like you know) you can change the precision of the display of a float.