the data-type 'float' displays decimal numbers. by default my compiler displays up-to 6 decimals. i want to see only two decimals. for eg , when the compiler performs the operation "c=2/3" it displays "0.666666667". i want to see only "0.67" in my output screen. so what necessary changes should i make in the C program?
+4
A:
You can use a format specifier to limit it to 2 decimal places when outputting the number using printf
.
int main() {
double d = 2.0 / 3.0;
printf("%.2f\n",d);
return 0;
}
Here's the output:
---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
0.67
> Terminated with exit code 0.
dcp
2010-08-11 21:10:57
+1
A:
You did not tell us how you display the value at all, therefore I guess you’re using something like printf("%f", x)
. You can prefix the “f” with a precision specification, which is a dot followed by a number, for example printf("%.2f", x)
.
Scytale
2010-08-11 21:12:59
+1
A:
The printf formatting for decimals is %. followed by the amount of decimal precision displayed followed by "f".
So displaying two decimal placess would be
printf("%.2f", i);
and displaying six decimal places would be
printf("%.6f", i);
Justin Hamilton
2010-08-11 21:15:35