How to make a float precise in C++.Help please

Suppose, I declared a float variable p;
float p;

now ,I want to take input for p;
Such as someone typed 12.123123 for p;
But when I’m working in program I want to make p only 2 decimal precised…
Like 12.12 and then do calculation on it…
Now I need help for 2 things…
How I can just cut off the value like 4.789 to 4.78
And how to make it precise like 4.789 to 4.79 (as the third decimal digit is more than 5).
How can I change float precision in these two ways in C and C++…
I ll appreciate any help.thanks…:slight_smile:

There exists a function to set precision for output but I’m not sure there’s one that directly does what you want.
http://www.cplusplus.com/reference/iomanip/setprecision/

Please read through the following post. It should explain some of the possible methods and where they fall short.

1 Like

well i can tell you this for C,how to truncate no. like 2.3456 to 2.34:->can use:printf("%0.mf",no);
here m refers to no. of digit you want after decimal in this case printf("%0.2f",no); would suffice.

Firstly you shouldn’t use float. Use double as it has more precision.

For the 2 things you mentioned-

Truncating digits beyond 2 decimal -

Simply multiply by 100 and cast to int. Now operate on the integer. And when you need decimal part simply take modulo 100.

Eg.

    d = 1.234  
 => d*100 = 123.4  
 => (int)123.4 = 123  
 => 123 % 100 = 23

Rounding up to 2 digits -

If you just want to print use

     printf("%.2lf", d);

However if you want to operate on it, you don’t need to round off. Use as much precision as available internally and ultimately when you need to print, just use above mentioned way.

In C++ include , and print as shown below-

     std::cout << std::setprecision(2) << d;
3 Likes
//