3

I am using .str(n, std::ios_base::scientific) to print ccp_dec_floats.

I've noticed that it rounds up.

I am using cpp_dec_float for accounting, so I need to round downward. How can this be done?

4

2 回答 2

3

它没有四舍五入。事实上,它确实是银行家的一轮:在 Coliru 上看 Live

#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 库中使用表达式模板,它有望编译成最佳代码。

于 2014-04-12T16:31:36.507 回答
1

我假设您正在尝试四舍五入到某个小数点,对吗?

标准四舍五入

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);              
}

祝你好运!

于 2014-04-12T16:45:58.663 回答