You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Double类型变量invValue赋值给类后转为Integer的问题求助

问题描述

我在向类赋值3个Double类型变量时遇到了问题:invValue在赋值给rv.invValue后被自动转换为Integer类型,丢失了小数部分。

相关代码

Function invRecord(invDate As Date, invQuantity As Double, invValue As Double) As invRecordClass
    
    Dim rv As New invRecordClass
    rv.invDate = invDate
    rv.invQuantity = invQuantity
    rv.invValue = invValue
    Set invRecord = rv
End Function

监视变量截图

监视变量截图

从截图可见,invValue以Double类型正常传入函数,但赋值给类的invValue属性后被舍入为整数。我需要让该变量保留小数部分,使用Single或Decimal类型均可,该如何处理?


解决办法

问题的核心几乎肯定是**invRecordClass类中invValue属性的声明类型错误**,和函数的赋值逻辑无关。你可以按以下步骤排查修复:

  1. 打开invRecordClass的类模块,检查invValue的定义:

    • 如果是直接用Dim invValue As Integer声明的字段,将类型修改为Double(或Single,根据精度需求选择)
    • 如果是用属性过程(Property Get/Property Let)实现的,需确保Property Let的参数类型和Property Get的返回类型都设置为Double/Single/Decimal,示例代码如下:
      Private m_invValue As Double
      
      Property Get invValue() As Double
          invValue = m_invValue
      End Property
      
      Property Let invValue(ByVal newValue As Double)
          m_invValue = newValue
      End Property
      
  2. 保存类模块后重新运行代码,invValue的小数部分即可正常保留。

如果是涉及货币计算这类需要高精度的场景,推荐使用Decimal类型,注意它不能直接用Dim声明,需借助Variant类型转换:

Private m_invValue As Variant

Property Get invValue() As Variant
    invValue = m_invValue
End Property

Property Let invValue(ByVal newValue As Variant)
    m_invValue = CDec(newValue)
End Property

内容的提问来源于stack exchange,提问作者Talch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:05:28