### float setting decimal places

I am trying to find out when using float in a calculation how to set the number of decimal places. For example my code below

 ``123456789`` ``````#include int main() { float x=123.0; float y=69.0; float answer=y*x; printf("the answer is %f\n",answer); return(0); } ``````

This returns an answer 8487.0000 I would like it not to show all the decimal places. However if the sum has decimal places I would like to select the number of decimal places shown

Thanks

Rodney
There is a command: cout.precision(n) which allows you to set the number of digits shown for a number. Personally, i prefer using c++ output rather than the printf command as it is easier(for me) to control it. Also, regarding your problem, cout will automatically output the integer if everything after the floating point is 0.
For instance:
 ``12345`` `````` cout.precision(8); float x=123.0; float y=69.0; float answer=y*x; cout << answer;``````

This will print 8487.

While:
 ``12345`` `````` cout.precision(8); float x=123.1; float y=69.0; float answer=y*x; cout << answer;``````

will print 8493.8994
Try this :

`printf("the answer is %4.0f\n",answer);`

It is all documented here - look at the example :

 http://www.cplusplus.com/reference/cstdio/printf/

HTH

Edit : Assumed the OP is doing C nor C++.
Last edited on
Topic archived. No new replies allowed.