Convert Textbox String to Double

The task is to take user entered textbox content, converting it to a field of type double.

As a part of a form I had a numeric entry field. The string value entered in this textbox to be converted to type double for saving in a database.

The public view of the textbox included the appropriate numeric validation. However, I prefer to test the entered content rather than assuming that this protection will be sufficient.

Given below is the text box definition.

<asp:TextBox is=”price” Visible=”True” runat=”Server />

I found that my old test for reading the value in a textbox and assigning it to a variable of type double had become unreliable.

To ensure the textbox string is correctly converted to a double, set the value to 0 if empty, or if it’s value doesn’t qualify as a double. I used the following:

Dim d as Double
If Double.TryParse(tbxPrice.Text, d) Then
  Price = convert.ToDouble(tbxPrice.Text)
Else
  Price = 0
End If

In the example above I first test to see if the content will convert to type double. If this works then we are good to make the conversion.

If the trial conversion fails then set the value to 0.

Whilst it’s possible to add checks to ensure that field values are of the correct type prior to submission I like to also add a check of the data when handling too. You can’t be too careful.