场景
double 保留8位小数,且四舍五入
错误方案1
typedef long long int64;
int main()
{
double v1 = 5726.867366095;
double v2 = 5837.754018494999;
const int64 N = pow(10, 8);
double newV1 = (int64)(round(v1 * N)) / double(N);
double newV2 = (int64)(round(v2 * N)) / double(N);
printf("%.8f\n", newV1);
printf("%.8f\n", newV2);
}
out:
5726.86736610
5837.75401850 << 错了
错误方案2
#include <boost/multiprecision/cpp_dec_float.hpp>
using boost::multiprecision::number;
using boost::multiprecision::cpp_dec_float;
typedef number<cpp_dec_float<50> > cpp_dec_float_50;
typedef long long int64;
int main()
{
cpp_dec_float_50 v1 = 5726.867366095; // v1 实际等于 5726.867366094999
cpp_dec_float_50 v2 = 5837.754018494999;
const int64 N = pow(10, 8);
double newV1 = (int64)round(v1 * N) / double(N);
double newV2 = (int64)round(v2 * N) / double(N);
printf("%.8f\n", newV1);
printf("%.8f\n", newV2);
}
out:
5726.86736609 << 错了
5837.75401849
正确方案
#include <boost/multiprecision/cpp_dec_float.hpp>
using boost::multiprecision::number;
using boost::multiprecision::cpp_dec_float;
typedef number<cpp_dec_float<50> > cpp_dec_float_50;
typedef long long int64;
int main()
{
cpp_dec_float_50 v1("5726.867366095"); // 为防止精度丢失,只能以字符串形式赋值,
cpp_dec_float_50 v2("5837.754018494999"); // 否则就是把错误的值赋给了对象,初值就错了
const int64 N = pow(10, 8);
double newV1 = (int64)round(v1 * N) / double(N);
double newV2 = (int64)round(v2 * N) / double(N);
printf("%.8f\n", newV1);
printf("%.8f\n", newV2);
}
out:
5726.86736610
5837.75401849