我必须为我的学校项目做excel的特殊类型的舍入。
如果数字大于#.5,我必须将其四舍五入。 如果数字等于#.5我必须将它四舍五入到最接近的偶数。 如果数字少于#.5,我必须将其四舍五入。
我希望有人能够帮助我。
Dim getal As Decimal = Nothing
Console.WriteLine("voer een nummer in")
getal = Console.ReadLine()
Dim dec As Integer = Nothing
Console.WriteLine("voer het aantal deciale in")
dec = Console.ReadLine()
Dim factor As Integer = 0
Dim floor As Decimal = 0
Dim decimaal As Decimal = 0
Dim antwoord As Decimal = 0
Dim percentage As Decimal = 0
Dim GetalTimesFactor As Decimal = 0
Dim OnNoukeurigheid As Decimal = 0
Dim VerFactor As Integer = 0
Dim HasFactor As Boolean = False
Dim notation As String = Nothing
Dim RoundUp As Decimal = 0
If getal > 1000 Then
While getal > 10
getal = getal / 10
VerFactor = VerFactor + 1
HasFactor = True
End While
Console.WriteLine("getal: " & getal)
End If
If getal < 0.0001 Then
While getal < 1
getal = getal * 10
VerFactor = VerFactor - 1
HasFactor = True
End While
End If
Select Case dec
Case 0
factor = 1
OnNoukeurigheid = 0.5
RoundUp = 1
Case 1
factor = 10
OnNoukeurigheid = 0.05
RoundUp = 0.1
Case 2
factor = 100
OnNoukeurigheid = 0.005
RoundUp = 0.01
Case 3
factor = 1000
OnNoukeurigheid = 0.0005
RoundUp = 0.001
End Select
GetalTimesFactor = getal * factor
floor = Decimal.Floor(GetalTimesFactor)
floor = floor / factor
decimaal = getal - floor
Console.WriteLine("floor: " & floor)
If decimaal > OnNoukeurigheid Then
floor = floor * factor
antwoord = floor + 1
antwoord = antwoord / factor
ElseIf decimaal = OnNoukeurigheid Then
antwoord = Decimal.Round(getal, dec, MidpointRounding.ToEven)
Else
Console.WriteLine("decimaal: " & decimaal)
Console.WriteLine("getal: " & getal)
percentage = (decimaal / getal) * 100
If percentage < 5 Then
Console.WriteLine("percentage is: " & Decimal.Round(percentage, 1) & "%")
antwoord = floor
Else
Console.WriteLine("percentage is: " & Decimal.Round(percentage, 1) & "%")
antwoord = floor + RoundUp
End If
End If
If HasFactor Then
notation = "E" & Format(VerFactor, "00")
End If
Console.WriteLine(antwoord & notation)
Console.ReadLine()
这是我在快递中所做的,它确实有效,但它不能在宏中工作
注意:抱歉荷兰语可变电影
答案 0 :(得分:1)
在VBA中它非常简单,因为VBA Round函数执行那种舍入:
Function VBARound(N As Double, Optional NumPlaces As Long = 0) As Double
VBARound = Round(N, NumPlaces)
End Function
NUMPLACES允许您选择舍入到整数以外的其他数据。
答案 1 :(得分:0)
我有点不确定这是你正在寻找的,因为在你的描述中你似乎暗示只寻找整数作为结果,所以我省略了函数的第二个变量,包含额外的小数点到把事情简单化。我认为我对你的舍入的解释与之前的答案略有不同,因此在.5的情况下,你会选择舍入到整个#都是偶数(不知道为什么会出现这种情况,但如果它在这里你就去了! )。
我为我的草率格式道歉......我是一名自学成才的VBA用户,所以可能会有更有效的方法:
Function CustomRound(N As Double)
If N - Application.WorksheetFunction.RoundDown(N, 0) = 0.5 Then
If Application.WorksheetFunction.RoundDown(N, 0) Mod 2 = 0 Then
CustomRound = Application.WorksheetFunction.RoundDown(N, 0)
Else
CustomRound = Application.WorksheetFunction.RoundUp(N, 0)
End If
Else
CustomRound = Round(N, 0)
End If
End Function