RWDecimalPortable
Class
RWDecimalPortable from the Essential Tools Module represents an arbitrary precision decimal fraction as a character string. This class exists mainly to provide a technique for retrieving exact precision numeric data types, such as monetary values. Some databases have methods for representing numeric values exactly. If the DB Interface Module fetched these values into
float or
double precision variables, there would be a risk of inaccuracy. Native C++ floating data types represent numbers using base 2; however, many noninteger decimal numbers, such as 0.1 and 19.7, cannot be exactly represented in base 2. For accounting or financial computations, the round-off error inherent in floating point arithmetic is unacceptable.
There are good reasons for using
RWDecimalPortable:
RWDecimalPortable provides exact representation and computation with decimal numbers. Using
RWDecimalPortable objects is the same as using the built-in floating types, except that there is no round-off error when working with decimal fractions, since
RWDecimalPortable uses base 10.
Since
RWDecimalPortable is part of the Essential Tools Module, it is the common representation used by Rogue Wave products.
The following example demonstrates the difference in accuracy between
RWDecimalPortable and the built-in type
double. In each case below, we add one cent to a zero-initialized variable one hundred times. We then remove one dollar, which should return the variable to zero. Using
RWDecimalPortable, the test succeeds; the account balances. Using
double, the value does not return to zero.
void usingDecimal() {
cout << "using RWDecimalPortable ... ";
RWDecimalPortable penny = "0.01";
RWDecimalPortable bank = 0;
for(int i = 100; i--;)
bank = bank + penny; // deposit 100 pennies
bank = bank - 1; // withdraw a dollar
cout << (bank == 0 ? "balances" : "doesn't balance") << endl;
}
void usingDouble() {
cout << "using double ... ";
double penny = 0.01;
double bank = 0;
for(int i = 100; i--;)
bank += penny; // deposit 100 pennies
bank -= 1; // withdraw a dollar
cout << (bank == 0 ? "balances" : "doesn't balance") << endl;
}
int
main() {
usingDecimal();
usingDouble();
return 0;
}