比如港币兑换人民币的兑换率是1.06
但是兑换率是在数据库里设置的,却被设置反了。0.9434,这是人民币兑换港币的兑换率。
我用1除以0.9434=1.0599957600169599321602713589146,本来应该是用两位小数点的,四舍五入为1.06
请教VB中哪个函数可以实现呢?
但是兑换率是在数据库里设置的,却被设置反了。0.9434,这是人民币兑换港币的兑换率。
我用1除以0.9434=1.0599957600169599321602713589146,本来应该是用两位小数点的,四舍五入为1.06
请教VB中哪个函数可以实现呢?
int(x*100+0.5)/100int(1/0.9434*100+0.5)/100=1.06注:精确到小数点后3位小数
int(x*1000+0.5)/1000
VBA.Math 的成员
Round to a given number of decimal places
返回参数的整数部分。语法Int(number)Fix(number)必要的 number 参数是 Double 或任何有效的数值表达式。如果 number 包含 Null,则返回 Null。说明Int 和 Fix 都会删除 number 的小数部份而返回剩下的整数。Int 和 Fix 的不同之处在于,如果 number 为负数,则 Int 返回小于或等于 number 的第一个负整数,而 Fix 则会返回大于或等于 number 的第一个负整数。例如,Int 将 -8.4 转换成 -9,而 Fix 将 -8.4 转换成 -8。Fix(number) μèóú£oSgn(number) * Int(Abs(number))
round(1/0.9434,2)
Dim wValue As Double
Dim tValue As Double
Round = Value
wValue = Value * 10# ^ ADigit + 0.5
tValue = Int(wValue)
If wValue - tValue > 0.99999999999999 Then tValue = tValue + 1
Round = tValue / 10# ^ ADigit
End Function
Dim wValue As Double
Dim tValue As Double
Round = Value
wValue = Value * 10# ^ ADigit + 0.5 * IIf(Value < 0, -1#, 1#)
tValue = Int(wValue)
If ((wValue - tValue) * IIf(Value < 0, -1#, 1#)) > 0.99999999999999 Then tValue = tValue + 1#
Round = tValue / 10# ^ ADigit
End Function
1.用 format 函数
2.用 formatcurrency 函数
3.用 round 函数
4.用 int(x*100+0.5)/100 可以精确到小数点后2位。
1.用 format 函数
2.用 formatcurrency 函数
3.用 round 函数
4.用 int(x*100+0.5)/100 可以精确到小数点后2位。
===================================================
1.format返回的是string消耗过大
2.同上
3.VB当中的Round使用的是银行式四舍五入,例round(0.565,2)≈0.56
4.对于部分数处理会由于浮点表示方式本来的不精确而使得结果不准确,就如我上面所给出的,需要做相应调整,下面给出一个相对简单点的:
Public Function Round(Number As Currency, Optional Position As Integer = 4) As Currency
'{CodeWizardStart}
On Error GoTo CodeWizardErrorHandle
'{CodeWizardEnd}
'Round(expression [,numdecimalplaces])
Round = IIf((Number * (10 ^ Position) - Int(Number * (10 ^ Position))) >= 0.5, Int(Number * (10 ^ Position)) + 1, Int(Number * (10 ^ Position))) / (10 ^ Position)
'{CodeWizardStart}
Exit Function
CodeWizardErrorHandle:
Err.Raise Err.Number,"Round",Err.Description
'{CodeWizardEnd}
End Function
Private Function RoundDouble(Number As Double, Optional Position As Integer = 4) As Double'{CodeWizardStart}
On Error GoTo CodeWizardErrorHandle
'{CodeWizardEnd}
'Round(expression [,numdecimalplaces])
RoundDouble = IIf((Number * (10 ^ Position) - Int(Number * (10 ^ Position))) >= 0.5, Int(Number * (10 ^ Position)) + 1, Int(Number * (10 ^ Position))) / (10 ^ Position)'{CodeWizardStart}
Exit Function
CodeWizardErrorHandle:
Err.Raise Err.Number,"RoundDouble",Err.Description
'{CodeWizardEnd}
End Function