Erzwinge das Abrunden von cpp_dec_float
-
21-12-2019 - |
Frage
ich benutze .str(n, std::ios_base::scientific)
zu drucken ccp_dec_float
S.
Mir ist aufgefallen, dass es aufrundet.
ich benutze cpp_dec_float
Für die Buchhaltung muss ich also abrunden.Wie kann das gemacht werden?
Lösung
Es wird nicht aufgerundet.Tatsächlich macht es die Runde des Bankiers:Sehen Sie es Lebe auf 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";
}
}
Drucke:
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
Wenn Sie also eine andere Art der Rundung wünschen, sollten Sie diese explizit schreiben
Hier ist ein allgemeiner Ansatz (Lebe auf 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;
}
was hoffentlich aufgrund des statisch bekannten Skalierungsfaktors und der Verwendung von zu optimalem Code kompiliert wird Ausdrucksvorlagen in der Boost Multiprecision-Bibliothek.
Andere Tipps
Ich gehe davon aus, dass Sie versuchen, auf eine bestimmte Dezimalstelle zu runden, richtig?
Standardrundung
double rounding_func(double in, double precision){
return round(in*pow(10,precision))/pow(10,precision);
}
Aber wie Ihr Titel sagt, versuchen Sie, eine Abrundung zu erzwingen, also denken Sie darüber nach
double rounding_func(double in, double precision){
return floor(in*pow(10,precision))/pow(10,precision);
}
Viel Glück!