做数据库类型的软件时常接触到“货币类型”数据,比如FOXPRO数据库里就有“currency”。处理此类数据时大家采用的什么方法呢?我开始用的double类型表达这些数据,后来发现有误差,猜想这是因为double类型数值在内存中以二进制方式保存,那么类似0.1这样的十进制数值是无法使用有限位数的二进制数值表达的。后来采用笨方法,采用__int64长整数来表示,当然是表示的货币类型数据的有效值,关于小数点位数需要另外处理。采用__int64表示后在进行货币类型数据的+、-、*运算时不会有误差。应该有更好的方法,望高手赐教,感谢!

解决方案 »

  1.   

    VC中支持CURRENCY,可以和数据库直接交换。
      

  2.   

    关于CURRENCY,MSDN中的介绍:*********
    A currency number stored as an 8-byte, two's complement integer, scaled by 10,000 to give a fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right. This representation provides a range of ±922337203685477.5807. The CURRENCY data type is useful for calculations involving money, or for any fixed-point calculation where accuracy is particularly important.typedef CY CURRENCY;
     
    The data type is defined as a structure for working with currency more conveniently:typedef struct  tagCY
        {
        LONGLONG int64;
        }    CY;#else
    // Real definition that works with the C++ compiler.
    typedef union tagCY {
        struct {         
    #ifdef _MAC          
            long          Hi;
            unsigned long Lo;
    #else                
            unsigned long Lo;
            long          Hi;
    #endif               
        };               
        LONGLONG int64;  
    } CY;                
    #endif
    #endif
    // Size is 8.
    typedef CY CURRENCY;*********
    资料是找到了,但是具体的用法还是不明白,例如定义了
    CURRENCY cy;
    如何保存“123.456”呢?
    如何计算几个CURRENCY类型数值的+、-、*、/运算呢?
    如何在EDITBOX里显示呢?晕晕晕,望高手赐教!
      

  3.   

    分析:
    CURRENCY作为一个结构或者联合来保存一个货币类型数值,内部主要是通过64位整数实现的。MSDN中提到CURRENTY可以表示“±922337203685477.5807”范围内的数,最多可以带4个小数。
    而 64位整数类型 LONGLONG 中没有表达小数点位置的信息啊……
      

  4.   

    to 中原草上飞:
    “A currency number stored as an 8-byte, two's complement integer, scaled by 10,000 to give a fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right.”
    这段话的意思好像就是说明你的问题呀:把LONGLONG的取值除以10000就是你的带浮点的数值。
      

  5.   

    to  qiuxiangyong(qxy):感谢!还是看的不够细致,忏悔中……另外,这个数被10000除后,看来是需要单独用两个整数类型存放小数点左边和右边的两部分。
    为保证精度,不适合用double存放除过后的小数。再次感谢楼上帮助!
      

  6.   

    期待VC中处理CURRENCY类型数据的常用方法,具体点的,看到这些方法后结贴。