Reputation: 95
When I calculated 5/2 the result is 2.500000, so I was wondering how I can limit the result of the float value to 2.50 instead. I am not using cout setprecision() or the fixed statement because I need the actual result of the arithmetic value to have only 2 decimal places.
Upvotes: 1
Views: 114
Reputation: 11
First of all, 2/5 gives 2 because writing it like this will do integer division. Only 2.0f/5.0f
will give you back a float.
Secondly, the only thing std::setprecision
does is modify how many digits are displayed on the console when you do std::cout
, it doesnt change the value of your variable or expression.
If you want to round your result to say one decimal place and not use standard functions, you could do something like
float a = 3.1415;
float b = ((int)(a*10+0.5))/10.0 // b is a rounded to one decimal place
but if you set std::setprecision
to say 5 decimal places, it will still show you all the zeros after the last decimal place.
Upvotes: 1
Reputation: 474
If you do not want to use certain decimal places, how about using ceil()
, floor()
, round()
?
Upvotes: 2