Round double to 3 points decimal [duplicate]

試著忘記壹切 提交于 2019-12-28 03:54:06

问题


Currently, I can round a double to an output stream using:

output.setf(std::ios::fixed,std::ios::floatfield);
output.precision(3);

But I'm given a double and I need to make the conversion before I insert it to a vector. So for instance, if the number -0.00078 appears then it equals to 0.000 and I won't need to save it. On the other hand, 1.0009 will become 1.001 (same as the precision function handles it).

How can I convert doubles like that in C++?


回答1:


A common trick is to do it with maths:

value = round( value * 1000.0 ) / 1000.0;

Where round will handle negative and positive values correctly... Something like this (untested):

inline double round( double val )
{
    if( val < 0 ) return ceil(val - 0.5);
    return floor(val + 0.5);
}

You'll still want to set the decimal places to 3 during output, due to floating point precision problems.




回答2:


Other answers here have given you a technique. But it's important to mention that not all values can be exactly represented in floating-point. 1.001 is a good example; the nearest possible value is 1.00099999999999988987.

So if your aim is to get strictly 3 decimal places, then the answer is: that's not possible.




回答3:


I know this is a very old post but I was looking for a solution to the same problem. However, I did not want to create a special function for it so I came up with the following:

#include <sstream>
#include <iomanip>
...
...
...
double val = 3.14159;
stringstream tmp;
tmp << setprecision(3) << fixed << val;
double new_val = stod(tmp.str());   // new_val = 3.143
tmp.str(string());                  // clear tmp for future use

Not sure if this is the best way to do it but it worked for me!




回答4:


You can multiply it by 1000 and then round (or truncate) it; this will give you a value 1000 times the 3-decimal place value. Note that, if you divide it by 1000 to get the 'rounded' value, you may end up w/ more than 3 decimal places (due to round off error).



来源:https://stackoverflow.com/questions/14369673/round-double-to-3-points-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!