如何使用自定义代码将小数转换为分数?

时间:2019-04-05 17:22:29

标签: vba reporting-services

我已经为SSRS报告创建了此自定义代码,以将分数隐式转换为小数,当我尝试运行该报告时,出现以下错误SSRS error。任何建议将不胜感激。代码在下面

********Public Function Dec2Frac(ByVal decimalNumber As Decimal, ByVal den As Integer)
As String
Dim fracString As String
        Dim dp As Decimal = decimalNumber Mod 1 'determine decimal portion
        Dim wn As Integer = CInt(Fix(decimalNumber)) 'determine whole number
portion
        Dim num As Integer = CInt(Math.Floor(dp * den + 0.5)) 'determine
numerator
        If num = 0 Then 'decimal rounds down to next whole number
            fracString = wn.ToString
        ElseIf num = den Then 'decimal rounds up to next whole number
            fracString = (wn + 1).ToString
        Else 'somewhere between
            Do Until num Mod 2 = 1
                num = CInt(num / 2)
                den = CInt(den / 2)
            Loop
            If wn > 0 Then
                fracString = wn.ToString & " " & num.ToString & "/" &
den.ToString
            Else
                fracString = num.ToString & "/" & den.ToString
            End If
        End If
        Return fracString 'return string
    End Function******

1 个答案:

答案 0 :(得分:0)

这对我有用:

可用于:Microsoft developer network 归功于:Eric Liu001

> Public Function Dec2Frac(ByVal f As Double) As String

   Dim df As Double
   Dim lUpperPart As Long
   Dim lLowerPart As Long

   lUpperPart = 1
   lLowerPart = 1

   df = lUpperPart / lLowerPart
   While (df <> f)
      If (df < f) Then
         lUpperPart = lUpperPart + 1
      Else
         lLowerPart = lLowerPart + 1
         lUpperPart = f * lLowerPart
      End If
      df = lUpperPart / lLowerPart
   End While
Dec2Frac =Cstr(lUpperPart\lLowerPart) & " " & CStr(lUpperPart mod lLowerPart) & "/" & CStr(lLowerPart)

End Function