Jump to content
  • Advertisement
Sign in to follow this  
inmysights

rounding

This topic is 4380 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!