Skip to content

Commit fd9273f

Browse files
committed
Significantly expand compile time rounding example
1 parent 3a65fdc commit fd9273f

File tree

1 file changed

+51
-6
lines changed

1 file changed

+51
-6
lines changed
Lines changed: 51 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,63 @@
11
// Copyright 2024 Matt Borland
22
// Distributed under the Boost Software License, Version 1.0.
33
// https://www.boost.org/LICENSE_1_0.txt
4-
4+
//
5+
// To define a global compile-time rounding mode
6+
// you must define the macro before inclusion of *ANY* decimal header
57
#define BOOST_DECIMAL_FE_DEC_DOWNWARD
6-
#include <boost/decimal.hpp>
8+
9+
#include <boost/decimal/decimal32_t.hpp> // For type decimal32_t
10+
#include <boost/decimal/literals.hpp> // For decimal literals
11+
#include <boost/decimal/iostream.hpp> // For decimal <iostream> support
12+
#include <boost/decimal/cfenv.hpp> // For rounding mode access
13+
#include <iostream>
14+
15+
void print_rounding_mode(const boost::decimal::rounding_mode current_mode)
16+
{
17+
// All 5 rounding modes are defined by the enum rounding_mode
18+
using boost::decimal::rounding_mode;
19+
20+
switch (current_mode)
21+
{
22+
case rounding_mode::fe_dec_downward:
23+
std::cout << "fe_dec_downward\n";
24+
break;
25+
case rounding_mode::fe_dec_to_nearest:
26+
std::cout << "fe_dec_to_nearest\n";
27+
break;
28+
case rounding_mode::fe_dec_to_nearest_from_zero:
29+
std::cout << "fe_dec_to_nearest_from_zero\n";
30+
break;
31+
case rounding_mode::fe_dec_toward_zero:
32+
std::cout << "fe_dec_toward_zero\n";
33+
break;
34+
case rounding_mode::fe_dec_upward:
35+
std::cout << "fe_dec_upward\n";
36+
break;
37+
}
38+
}
739

840
int main()
941
{
1042
using namespace boost::decimal::literals;
43+
using boost::decimal::decimal32_t;
1144

12-
constexpr auto lhs {"5e+50"_DF};
13-
constexpr auto rhs {"4e+40"_DF};
14-
constexpr auto downward_res {lhs - rhs};
45+
// This uses one of the same examples from our runtime rounding mode example
46+
// Now we can see the effects on the generation of constants,
47+
// since we can static_assert the result
48+
49+
constexpr decimal32_t lhs {"5e+50"_DF};
50+
constexpr decimal32_t rhs {"4e+40"_DF};
51+
constexpr decimal32_t downward_res {lhs - rhs};
1552
static_assert(downward_res == "4.999999e+50"_DF, "Incorrectly rounded result");
1653

17-
return 0;
54+
std::cout << "The default rounding mode is: ";
55+
print_rounding_mode(boost::decimal::rounding_mode::fe_dec_default);
56+
57+
// Here we can see that the rounding mode has been set to something besides default
58+
// without having had to call fesetround
59+
//
60+
// This works with all compilers unlike changing the rounding mode at run-time
61+
std::cout << "The current rounding mode is: ";
62+
print_rounding_mode(boost::decimal::fegetround());
1863
}

0 commit comments

Comments
 (0)