How RWDecimal classes cast ints and doubles

Article ID: 1022
Last updated: 05 Feb, 2008
Article ID: 1022
Last updated: 05 Feb, 2008
Revision: 1
Views: 2860
Posted: 15 Jan, 1998
by Dean J.
Updated: 05 Feb, 2008
by Dean J.
Problem


How can ints and doubles get cast to RWDecimal classes?



Action


Money.h++ types can automatically cast from an int to an RWDecimal (or any of its derived types), so the following code would run correctly:
int shares = 0;
RWDecimal52 price(100),principal;
principal = shares * price;
There is a constructor in RWDecimal that takes an int as a parameter. This is because ints are stored as exact values so there is not a problem in converting an int into an RWDecimal. Converting a float to an RWDecimal is a little more complicated. The way floats are stored in C++ is inexact (which is one of the reasons for creating Money.h++ in the first place). If you want to convert a float to an RWDecimal, you need to use the from member function. This was done deliberately because the results of calling this function may be inexact. Here is how you would write the same code if the shares variable was a float.
float shares = 0;
RWDecimal52 price(100),principal;
principal = RWDecimal52::from(shares) * price;
This article was:   Helpful | Not helpful
Report an issue
Article ID: 1022
Last updated: 05 Feb, 2008
Revision: 1
Views: 2860
Posted: 15 Jan, 1998 by Dean J.
Updated: 05 Feb, 2008 by Dean J.

Others in this category