A
AMDRIT
Given:
?System.Math.Round(161.5D,0)
162.0
?System.Math.Round(162.5D,0)
162.0
?System.Math.Round(163.5D,0)
164.0
In either C# '05 or VB.Net '05, can anyone explain the inconsistancy? Is
there a better way to round a value in a consistant manner?
I have created a function for it until I have a better way.
''' <summary>
''' Rounds a decimal value to the nearest whole number integer.
''' </summary>
''' <param name="numberToRound"></param>
''' <returns></returns>
Public Shared Function Round(ByVal numberToRound As Decimal) As Integer
' Rounds a value to the nearest whole number integer
' inputs:
' 1. ByVal Decimal
' return: Long
Dim bNegative As Boolean
Dim iResult As Decimal
'Flag to let us know we were working with a negative number
bNegative = numberToRound < 0
'Check to see if the decimal portion is greater than or equal to .5
If Abs(Abs(numberToRound) - Int(Abs(numberToRound))) >= 0.5D Then
'Round up
iResult = -Int(-(Abs(numberToRound)))
Else
'Round down
iResult = Abs(numberToRound) - (Abs(numberToRound) -
Int(Abs(numberToRound)))
End If
'Check our flag and convert to negative accordingly
If bNegative Then iResult = -iResult
Return iResult
End Function
?System.Math.Round(161.5D,0)
162.0
?System.Math.Round(162.5D,0)
162.0
?System.Math.Round(163.5D,0)
164.0
In either C# '05 or VB.Net '05, can anyone explain the inconsistancy? Is
there a better way to round a value in a consistant manner?
I have created a function for it until I have a better way.
''' <summary>
''' Rounds a decimal value to the nearest whole number integer.
''' </summary>
''' <param name="numberToRound"></param>
''' <returns></returns>
Public Shared Function Round(ByVal numberToRound As Decimal) As Integer
' Rounds a value to the nearest whole number integer
' inputs:
' 1. ByVal Decimal
' return: Long
Dim bNegative As Boolean
Dim iResult As Decimal
'Flag to let us know we were working with a negative number
bNegative = numberToRound < 0
'Check to see if the decimal portion is greater than or equal to .5
If Abs(Abs(numberToRound) - Int(Abs(numberToRound))) >= 0.5D Then
'Round up
iResult = -Int(-(Abs(numberToRound)))
Else
'Round down
iResult = Abs(numberToRound) - (Abs(numberToRound) -
Int(Abs(numberToRound)))
End If
'Check our flag and convert to negative accordingly
If bNegative Then iResult = -iResult
Return iResult
End Function