Marco Marco - 1 month ago 5x Question

How to make give 5 significant digits in the textbox output?

I want to have only 5 significant digits in my textbox output. May I know what VB function does this. Thanks


Use the Validating event to reformat the entered number. You'll want to use an ErrorProvider to report input errors back the user.

To get a fixed number of significant digits, you need to dynamically create the formatting string for the number, based on the entered value. You can use Math.Log10() to calculate the number of digits required in the fraction. Like this:

Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
    Dim value As Double
    If Not Double.TryParse(TextBox1.Text, value) Then
        ErrorProvider1.SetError(TextBox1, "Please enter a valid number")
        ErrorProvider1.SetError(TextBox1, "")
        Dim intDigits As Integer = 0
        If value <> 0 Then intDigits = CInt(Math.Truncate(Math.Log10(Math.Abs(value))))
        If intDigits >= 0 Then intDigits += 1
        Dim fracDigits = 5 - intDigits
        If fracDigits < 0 Then fracDigits = 0
        Dim format = "F" + fracDigits.ToString()
        TextBox1.Text = value.ToString(format)
    End If
End Sub