我正在使用.str(n, std::ios_base::scientific)来打印生成ccp_dec_floats。

我注意到它已经圆起来了。

我正在使用cpp_dec_float进行会计,所以我需要向下旋转。怎么做到这一点?

有帮助吗?

解决方案

它不圆。事实上,它是银行家的回合:看到它

#include <boost/multiprecision/number.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>

namespace mp = boost::multiprecision;

int main()
{
    using Dec = mp::cpp_dec_float_50;

    for (Dec d : { 
            Dec( "3.34"),   Dec( "3.35"),   Dec( "3.38"),
            Dec( "2.24"),   Dec( "2.25"),   Dec( "2.28"),
            Dec("-2.24"),   Dec("-2.25"),   Dec("-2.28"),
            Dec("-3.34"),   Dec("-3.35"),   Dec("-3.38"),
            })
    {
        std::cout     << d.str(2, std::ios_base::fixed) 
            << " -> " << d.str(1, std::ios_base::fixed) << "\n";
    }
}
.

打印:

3.34 -> 3.3
3.35 -> 3.4
3.38 -> 3.4
2.24 -> 2.2
2.25 -> 2.2
2.28 -> 2.3
-2.24 -> -2.2
-2.25 -> -2.2
-2.28 -> -2.3
-3.34 -> -3.3
-3.35 -> -3.4
-3.38 -> -3.4
. 所以如果你想要另一种四舍五入,你想明确地写作它

这是一种通用方法( live在coliru

template <int decimals = 0, typename T>
T round_towards_zero(T const& v)
{
    static const T scale = pow(T(10), decimals);

    if (v.is_zero())
        return v;

    // ceil/floor is found via ADL and uses expression templates for optimization
    if (v<0)
        return ceil(v*scale)/scale;
    else
        // floor is found via ADL and uses expression templates for optimization
        return floor(v*scale)/scale;
}
.

希望由于静态已知的比例因子和升压多点库中的使用表达式模板使用而被降至最佳代码。

其他提示

我假设你试图达到一定数点的小数点,正确?

标准舍入

double rounding_func(double in, double precision){
   return round(in*pow(10,precision))/pow(10,precision);              
}
.

但随着你的标题说,你试图强迫它左转,所以考虑

double rounding_func(double in, double precision){
   return floor(in*pow(10,precision))/pow(10,precision);              
}
.

祝你好运!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top