Search code examples
visual-c++mfccomvariant

How is CY or CURRENCY union used in VC++?


I have to handle Variant type VT_CY in the server I am working on. This is link to the data type.

CURRENCY union

Although it describes the type, I could not find any example of its usage. Please provide the example for the same.


Solution

  • As other commenters have noted, the structure of a CY is well-known, and you can therefore program your own conversions and manipulations. However, I usually prefer to rely on the API that Microsoft has provided for CY instances. Take a look at the following links.

    You should try to limit conversion as much as possible. If you have two CY structs, use arithmetic functions like VarCyAdd instead of converting the CY structs to floating-point types. This will reduce floating point errors. When you have manipulated the CY structs as appropriate, you can use VarBstrFromCy to generate a string representation of the value. Again, this is better than converting the final result to a floating-point value before formatting the floating-point value to a string.

    All of the previous holds true for DECIMAL types as well.

    There are similar functions for VARIANT structs. If you have two VARIANT structs that contain numeric values (anything from an INT to a DECIMAL to a CY), you can use functions like VarAdd to add the two VARIANT structs in a well-defined manner. For example, if you call that function on two VARIANT structs that each contain a CY value, the result will be a VARIANT containing a new CY value. If you add a VARIANT containing a CY to a VARIANT containing a DECIMAL, you end up with a VARIANT containing a DECIMAL.