In this example I will show you
how to take a decimal number in Visual
Basic and round it to a specified number
of decimal places. Follow the example
below.
- Start Visual Basic, by
selecting it from the start menu.
- When VB has loaded, a window
appears. Click on Standard-EXE
which will create form1 by
default.
- On the toolbox to the right
of form1 select the command
button and drag it to a resonable
size on the form.
- Open up form1's code window
by double clicking on the command
button.
- A new window will
appear. Delete everything
in that window and type the
following:
Private Sub Command1_Click()
MsgBox Round(12.3265, 2)
End Sub
Function Round(nValue As Double, nDigits As _
Integer) As Double
Round = Int(nValue * (10 ^ nDigits) +
_
0.5) / (10 ^ nDigits)
End Function
Run the project by
pressing F5. When the from has loaded
click on the command button and 12.33 is
returned.
But Rick Rothstein submitted some easier ways
to round a number:
Round =
Val(Format(num, "0." & String(dec,
"#")))
or
Round =
Format(num, "0" & IIf(dec,
".", "") & String(dec,
"#"))
Charles L. Flatt proposed this method:
Here's a further addition for two decimal
places, and corrects against floating point errors.
This is very important to calculating financial
figures. Note: This is for arithmetic,
not banker's, rounding.
Private Function
RoundA(ByVal num As Currency) As Currency
' If currency datatype isn't used, correct
arithmetic rounding isn't achieved
' 1.015 = 1.02, 1.025 = 1.03
RoundA = Int(num * 100 + 0.5) / 100
End Function
This function could be modified to round up to
four decimal places.
|