I have a text box that displays a calculation result to 7 decimal points.
Can anyone help me to round that number off to 4 decimal places??
THANX
Printable View
I have a text box that displays a calculation result to 7 decimal points.
Can anyone help me to round that number off to 4 decimal places??
THANX
There is a property call Decimal Places. I think it defaults to AUTO, but you can set it to 4.
You could use the Format Function.
But, the rounding that VB does is not always what you want.Code:Private Sub Command1_Click()
Dim dblNumber As Double
dblNumber = 10.12345
Text1.Text = Format(dblNumber, "##,###.0000")
End Sub
Private Sub Command1_Click()
Text1 = Round(2.46743786447957, 7)
End Sub
Format function:
Will cut after a given number of decimal places
E.g.: 2.453749, using format to five decimal places will give 2.45374
Round function will actually round the number off.
Private Sub Text1_Click()
Dim n
n = 1.12345678
Text1.Text = Round(n, 4) ' your result = 1.1235
' if you need to truncate, search for the
' dot and then copy to the right 4 chars
End Sub
I do not remember who originally posted this code, but it does a better job of rounding than VB.
Code:'rounding a number
Function RoundNumber(lNumber, Optional iDecimalPlaces As Integer = 1)
RoundNumber = Int(lNumber * (10 ^ iDecimalPlaces) + 0.5) / (10 ^ iDecimalPlaces)
End Function
'2 represents the number of places you want after the decimal
Private Sub Command1_Click()
Dim dblNumber As Double
dblNumber = InputBox("Enter a number to round")
MsgBox RoundNumber(dblNumber, 2)
End Sub
I could find the decimal property on the default text box.
This is just a different way of doing it.
Paul BousaCode:private sub text1_lostfocus()
text1 = format(text1,"#0.0000")
You could also use this code to round the number to 4 decimal places when the field loses focus.
Code:Function RoundNumber(lNumber, Optional iDecimalPlaces As Integer = 1)
RoundNumber = Int(lNumber * (10 ^ iDecimalPlaces) + 0.5) / (10 ^ iDecimalPlaces)
End Function
'4 represents the number of places you want after the decimal
Private Sub text1_lostfocus()
Text1.Text = RoundNumber(Text1.Text, 4)
End Sub
Just an FYI. I started using the RoundNumber Function that was posted on these boards because the Round Function in VB does the following.
If you use Round(1.12345,4) the result is 1.1234
If you use Round(1.12355,4) the result is 1.1236
The round function in VB will round down when the value in the position to round to is even. It will round up when the value is odd.
Strange, but true.