rounding

Started by
3 comments, last by Krohm 17 years, 6 months ago
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
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.
Disclaimer: "I am in no way qualified to present advice on any topic concerning anything and can not be held responsible for any damages that my advice may incurr (due to neither my negligence nor yours)"
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.

Previously "Krohm"

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;}
Isn't just better to use floorf then?

Previously "Krohm"

This topic is closed to new replies.

Advertisement