vb的一个计算问题
Public Function ChangeInteger(fCIData As Double, cPrecision As String) As String
'根据精度化整
Dim Hstep As Double, xys As Double
Hstep = val(cPrecision) * 0.1
If val(cPrecision) = 3 Then
Hstep = 0.2
End If
xys = fCIData / Hstep
If val(Abs(xys) - Fix(Abs(xys))) > 0.5 Then
xys = Fix(Abs(xys)) + 1
End If
If val(Abs(xys) - Fix(Abs(xys))) < 0.5 Then
xys = Fix(Abs(xys))
End If
If val(Abs(xys) - Fix(Abs(xys))) = 0.5 Then
If Fix(Abs(xys)) / 2 = Fix(Fix(Abs(xys)) / 2) Then
xys = Fix(Abs(xys))
Else
xys = Fix(Abs(xys)) + 1
End If
End If
If fCIData < 0 Then
xys = -xys
End If
If val(cPrecision) >= 1 And val(cPrecision) < 10 Then
ChangeInteger = Format$(Fix(xys * Hstep * 10) / 10, "0.0")
End If
If val(cPrecision) >= 0.1 And val(cPrecision) < 1 Then
ChangeInteger = Format$(Fix(xys * Hstep * 100) / 100, "0.00")
End If
If val(cPrecision) >= 0.01 And val(cPrecision) < 0.1 Then
ChangeInteger = Format$(Fix(xys * Hstep * 1000) / 1000, "0.000")
End If
If val(cPrecision) >= 0.001 And val(cPrecision) < 0.01 Then
ChangeInteger = Format$(Fix(xys * Hstep * 10000) / 10000, "0.0000")
End If
End Function
这是我的一个计算化整的一个函数,当我的入参是(0.0175,0.05)或者是(0.0275,0.05)得到的值应该是0.02或者是0.03,进过debug发现是val(Abs(xys) - Fix(Abs(xys)))这个判断出问题,虽然Abs(xys)=3.5, Fix(Abs(xys))=3 但得到的值是0.499999999999999而不是0.5.不知道有什么好办法可以改良让val(Abs(xys) - Fix(Abs(xys)))当类似入参那样的值得到的结果是0.5。不要用四舍五入的方法,这样可能会出现一些没有意料到得数据的问题被判大或判小了。