Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Rounding Function

Status
Not open for further replies.

0CODE

Programmer
Feb 8, 2004
63
CA
why does the built in rounding function (math.round) sometiems round down when the decimal is "5" which it should go up?
 
It is the form of rounding that they employ. It is actually supposed to do that.

Math.Round uses "Rounding to the Nearest".


From the Decimal.Round documentation (which also uses Rounding to the Nearest")...

"When d is exactly halfway between two rounded values, the result is the rounded value that has an even digit in the far right decimal position. For example, when rounded to two decimals, the value 2.345 becomes 2.34 and the value 2.355 becomes 2.36. This process is known as rounding toward even, or rounding to nearest."
 
yeah i noticed that about the even / odd #, but I found a way to fix it

thanks
 
If you need x.5 to round up, you can always add .5 to the value and take its Floor. That will give you the traditional rounding many of us are familiar with.

Code:
Math.Floor( 2.49999999999999 + 0.5 )
--> 2

Math.Floor( 2.5 + 0.5 )
--> 3

Works with decimal types to 15 significant digits.
 
but that method makes a problem if ur trying to round to 2 decimals, or 3 for ex.

here is what ive made up that works for me:

Public Function round2(ByVal value As String, Optional ByVal decimals As Integer = 2)
Dim subdecimal As Decimal = 1 / 10 ^ value.Length
Dim decval As Double = CDbl(value)

If Math.Round(decval, decimals) < Math.Round(value + subdecimal, decimals) Then
round2 = Math.Round(value + subdecimal, decimals)
Else
round2 = Math.Round(decval, decimals)
End If

End Function
 
*just made a small mistake (although it still works) ---> just change everything after the declaring of "decval" that is "value" to "decval"

and which rounding do you prefer, the normal way or the new one?
 
but that method makes a problem if ur trying to round to 2 decimals, or 3 for ex.

<sarcasm>Well, yes. But who would ever want to do THAT?</sarcasm>

Code:
Private Function RoundMe(ByVal value As Decimal, ByVal places As Integer) As Decimal
  RoundMe = Math.Floor((value * (10 ^ places)) + 0.5) / (10 ^ places)
End Function
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top