试试这个: Private Function tonum(kk!) As Integer Dim i!, j As Integer i = Abs(kk - Round(kk)) If i >= 0.5 Then j = Fix(kk) + 1 Else j = Fix(kk) End If tomnum = j End Function
Private Function myformat(num As Single, i As Integer) As Single Dim str As String, j As Integer str = "############" If i = 1 Then str = str & ".0" End If If i > 1 Then str = str & ".0" For j = 2 To i str = str & "0" Next j End If myformat = Format(num, str) End FunctionPrivate Sub Command1_Click() Dim x As Single x = 12.2535 Debug.Print myformat(x, 1) Debug.Print myformat(x, 3) End Sub result: 12.3 12.254
Private Function myRound(ByVal val As Double, p As Integer) As Double myRound = Format(val, "." & String(p, "#")) End Function
ROUND 就是这么定义的。简单方法:int(x + 0.5)
Private Function myRound(ByVal val As Double, p As Integer) As Double myRound = Int(val * 10# ^ p + 0.5) / (10# ^ p) End Function Debug.Print myRound(2.54555, 0) Debug.Print myRound(2.54555, 1) Debug.Print myRound(2.55555, 2) Debug.Print myRound(2.55555, 7) 结果: 3 2.5 2.56 2.55555
四舍六入五成双用of123的int(x + 0.5)方法最好
dim n as integer '为保留的小数点位数 dim x as single '为操作数 int(x*10^n+0.5)/10^n
format(13.5,"############")=14
format(12.5,"############")=13
这个round是比较挫.
=======================
x=int(x+0.5)
Private Function tonum(kk!) As Integer
Dim i!, j As Integer
i = Abs(kk - Round(kk))
If i >= 0.5 Then
j = Fix(kk) + 1
Else
j = Fix(kk)
End If
tomnum = j
End Function
Dim str As String, j As Integer
str = "############"
If i = 1 Then
str = str & ".0"
End If
If i > 1 Then
str = str & ".0"
For j = 2 To i
str = str & "0"
Next j
End If
myformat = Format(num, str)
End FunctionPrivate Sub Command1_Click()
Dim x As Single
x = 12.2535
Debug.Print myformat(x, 1)
Debug.Print myformat(x, 3)
End Sub
result:
12.3
12.254
myRound = Format(val, "." & String(p, "#"))
End Function
myRound = Int(val * 10# ^ p + 0.5) / (10# ^ p)
End Function Debug.Print myRound(2.54555, 0)
Debug.Print myRound(2.54555, 1)
Debug.Print myRound(2.55555, 2)
Debug.Print myRound(2.55555, 7)
结果: 3
2.5
2.56
2.55555
dim x as single '为操作数
int(x*10^n+0.5)/10^n
<5 舍掉
=5 凑偶数
>5 入上即:4舍6入5凑偶
例如:
ROUND(12.5)=12
ROUND(11.5)=12
ROUND(12.49999999999)=12
ROUND(12.50000000001)=13