c++ - 强制 cpp_dec_float 向下舍入

标签 c++ boost rounding multiprecision

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

我注意到它四舍五入了。

我正在使用 cpp_dec_float 进行记账,所以我需要向下取整。如何做到这一点?

最佳答案

它不会四舍五入。事实上,它确实是银行家的回合:参见 Live On Coliru

#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 On 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;
}

由于静态已知比例因子和 Boost Multiprecision 库中表达式模板的使用,它有望编译成最佳代码。

关于c++ - 强制 cpp_dec_float 向下舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23032596/

相关文章:

c++ - 当类在单独的文件中时,使用 asio 独立的段错误

c++ - 在 boost 图形库中绑定(bind)到 std::vector 的外部属性映射

c++ - 在 C++ 中将数字显式舍入到小数点后 7 位以上

c++ - 是否可以在ODBC和C++中使用Flyway?

c++ - 如何在保持圆周位置的同时缩放多边形

c++ - Boost:API 在 1.46.1 和 1.58.0 之间发生变化?

javascript - 如何在 Jquery/Javascript 中四舍五入 parseFloat 结果?

objective-c - Objective-C 中如何将 double 值舍入为下一个整数值?

c++ - msvs 2015中模板实例化错误

c++ - OpenGL 3D 选择