|
保留有效位数并四舍六入2004-11-26新*摘自一位网友的提问:
引用:
既要四舍六入又要保留有效数字位数怎样设置?
各位大侠:因工作需要数据要求保留3位(或2位、4位)有效数字,且必须按4舍6入准则处理,如1.254 0.2515 1.225 1.22501 12300 保留3位有效数字且4舍6入分别为: 1.25 0.252 1.22 1.23 1.23E+04(或1.23× 10的四次方) 该用何函数,请各位高手帮忙啦! 谢谢!
特别感谢chenjun版主及其对修约规则的精辟解析和对本贴提出的许多宝贵建议。[em17][em17][em17][em17][em17][em17][em23][em24]
特别说明:
引用:
请注意工作表函数和自定义函数ROUND2都有一个参数作为有效位进位开关,当进位开关为1时,可以处理此例情况:0.99保留1位写成1.0,也就是多保留了一位;当进位开关为0时,0.99保留1位写成1。以满足一些特殊需要。详细分析请见本贴中chenjun版主的论述。
EXCEL限制:在选择有效位进位选项时,工作表函数在处理有效位12位以上时部分数值不准,自定义函数round2()则在15位以上时出现类似情况。这个问题将进一步修正。
1、工作表函数解法:
名称定义
NUM=解法!$A3
DIG=解法!$H$2
TRN=解法!$G$2
OFF=ROUND(ABS(NUM),-(INT(LOG(ABS(NUM)))-DIG+1))-(--RIGHT(NUM/10^(INT(LOG(ABS(NUM)))-DIG+1),2)=0.5)*(MOD(RIGHT(INT(ABS(NUM)/10^(INT(LOG(ABS(NUM)))-DIG+1)),1),2)=0)*10^INT(LOG(ABS(NUM))-DIG+1)
PLS=(10^INT(LOG(OFF))=OFF)*(OFF>ABS(NUM))*TRN
RST=IF(NUM=0,"0",IF(SIGN(NUM)=-1,"-","")&TEXT(OFF,"0"&IF((DIG=1)*(INT(LOG(OFF))=0)*(PLS=0),"",IF((INT(OFF)=OFF)*(DIG=1)*(PLS=0),"",".")&REPT("0",DIG+PLS-1))&IF(LOG(OFF)<1,REPT("0",-INT(LOG(OFF))),"E+###")))
2、自定义函数解法
'ROUND2(数值,保留有效位数,返回文本或数值,遇进位时增加有效位开关)
Function Round2(Num As Double, DIG As Byte, Optional TorV As Boolean, Optional Trn As Boolean) As Variant
Dim Temp1 As Double
Dim TFM As String
Dim Temp2 As String
Dim Tempoff As Double
'-----------------------------------------------
' 鉴于vba中的round与工作表的round不同,这里
' 使用工作表中的round,因为vba中的round有问
' 题。vba中特别同时保留两个round应该是有目的吧,
' 其他函数或操作符一般只有一个
'-----------------------------------------------
If Num = 0 Then
Temp1 = 0
Temp2 = "0"
GoTo ExitFn
End If
With Application.WorksheetFunction
Tempoff = Abs((--Right(Num / 10 ^ (Int(.Log(Abs(Num))) - DIG + 1), 2) = 0.5) _
* ((--Right(Int(Abs(Num) / 10 ^ (Int(.Log(Abs(Num))) - DIG + 1)), 1) _
Mod 2) = 0)) * 10 ^ Int(.Log(Abs(Num)) - DIG + 1)
Temp1 = .Round(Abs(Num), -(Int(.Log(Abs(Num))) - DIG + 1))
Temp1 = Temp1 - Tempoff
Trn = Trn And (10 ^ Int(.Log(Temp1)) = Temp1 And Temp1 > Abs(Num))
If DIG > 14 And Trn Then
Temp2 = "有效位数超过14位不能进位"
GoTo ExitFn
End If
If DIG = 1 And Int(.Log(Abs(Temp1))) = 0 And Not Trn Then
TFM = ""
Else
If Not (DIG = 1 And Int(Temp1) = Temp1 And Not Trn) Then TFM = TFM & "."
TFM = TFM & .Rept("0", DIG + Abs(Trn) - 1)
End If
TFM = "0" & TFM
If Int(.Log(Temp1)) < 0 Then
TFM = TFM & .Rept("0", -Int(.Log(Temp1)))
ElseIf Int(.Log(Temp1)) > 0 Then
TFM = TFM & "E+###"
End If
Temp1 = Temp1 * Sgn(Num)
Temp2 = .Text(Temp1, TFM)
End With
ExitFn:
If TorV Then
Round2 = Temp2
Else
Round2 = Temp1
End If
End Function
[ 本帖最后由 apolloh 于 2008-11-8 17:56 编辑 ] |
|