我正在使用 .str(n, std::ios_base::scientific)
来打印 ccp_dec_float
s。
我注意到它四舍五入了。
我正在使用 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/