Question

I have a label that shows too many decimal values.

For example,

textbox1 = 22  
textbox2 =  7  
label1 = textbox2/textbox1

I want label1 turn to 31.8 but it always turn to 31.8181811818181818881

I have already tried:

    Dim label1 As String
    label1 = (CInt(Me.textbox2.Text) / CInt(Me.textbox1.Text)) * 100
    Format(label1, "0.00")
    Form3.label1.Text = label1 + " %" 
Was it helpful?

Solution

Acc. to your comment:

@KashishArora yes

I will do it in a very very simple way!

Explanation

We will first simply divide Textbox1 with Textbox2 and store the value in a label and then declare an integer a as label1.text (it isn't necessary to do it in variable, you can do directly). Then we will use the Math.Round control and specify the number of decimals we want (1 or 2).

And then finally, store the value of a back to Label1.

Code And Example

Label1.Text = Val(TextBox2.Text) / Val(TextBox1.Text)
Dim a As Double = Label1.Text
a = Math.Round(a, 2) '2 is number of decimal places
Label1.Text = a
'All the things you want to do with this.

I hope it works perfectly!

OTHER TIPS

Use String.Format()...

Dim label1 As String
label1 = (CInt(Me.textbox2.Text) / CInt(Me.textbox1.Text)) * 100
label1 = String.Format("{0:0.0}", label1)
Form3.label1.Text = label1 & " %" 

Just use the combination of substring and lastindexof

label1 = textbox2/textbox1

Dim labelText As String = label1.Text
labelText = labelText.Substring(0, labelText.LastIndexOf(".") +2)  + "%"

You're all making this more complex than it is. Decimal.ToString has an overload where you can pass a standard or custom numeric format string.

In your case on should use the F{n} format specifier where {n} is the precision specifier indicating the desired number of decimal places.

label1.Text = (Decimal.Parse(textBox1.Text) / Decimal.Parse(textbox2.Text)).ToString("F2")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top