Sign in to follow this  
inmysights

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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
(1) add 0.5, then
(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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this