# rounding

## Recommended Posts

Here is a good one. #include <iostream> #include <cmath> #include <iomanip> int main() { float pi=3.14159; cout.setprecision(3); cout << pi; } when you run it you get 3.142. I don't want c++ to round it up to 3.142 I just wanna show 3.141 how in the world is this done? thank you for your help

##### Share on other sites
I don't know of a better way (it's very possible there is one), but you can multiply by 1000, use floor() on the value, then divide by 1000.

##### Share on other sites
It's rounded only in the output because this is the correct thing to do when displaying numbers with limited precisions.
If you do the computations and check the result you'll find out it's just in the standard FP32 error.
If you want to truncate on output, maybe there's a ios::truncate flag but I'm not sure.

##### Share on other sites
I don't know whether cout can truncate as opposed to rounding off a number, but if it can't truncate directly there is a fairly simple way to get the same effect.

To round off a numberto the nearest 1, one would generally
(2) truncate the number, as you would if you were simply truncating, rather than rounding

In this case, truncating a number would be the identical to rounding the same number - 0.5. The same principle works for rounding/truncating to any precision.

So
#include <iostream>#include <cmath>#include <iomanip>int main(){float pi=3.14159;cout.setprecision(3);cout << pi - 0.0005;}

##### Share on other sites
Isn't just better to use floorf then?

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627676
• Total Posts
2978582

• 11
• 12
• 10
• 12
• 22