LabRat
LabRat

Reputation: 2014

VB.net convert , to decimal (order of placement)

Hi I have a textbox which dose some math calculations perfect if you work with decimals not so if you work with commas.. the first option i explored was to just accept numbers and decimals in a masked textbox... but why? some of us have learned to use commas since we first started school... so my idea is to have a textbox which searches for commas and turns them into decimals for the user.

I have the following code but as example if I type in 2,5 my conversion becomes 25. so yes i have converted the comma to decimal but have lost its placing. The question thus being how can I do my conversion properly with the right decimal placement?

If TextBox13.Text.Contains(",") Then
TextBox13.Text = Replace(TextBox13.Text, ",", ".")
dim test as double textbox1.text
msgbox(test)
End If

Upvotes: 0

Views: 84

Answers (2)

Claudius
Claudius

Reputation: 1911

Why not make comma an illegal entry. Don't you block entering letters anyway.

Private Sub textBox1_KeyPress(sender As Object, e As KeyPressEventArgs)
    e.Handled = SingleDecimal(sender, e.KeyChar)
End Sub

Public Function SingleDecimal(sender As System.Object, eChar As Char) As Boolean
    Dim chkstr As String = "0123456789."
    If chkstr.IndexOf(eChar) > -1 OrElse eChar = Constants.vbBack Then
        If eChar = "." Then
            If DirectCast(sender, TextBox).Text.IndexOf(eChar) > -1 Then
                Return True
            Else
                Return False
            End If
        End If
        Return False
    Else
        Return True
    End If
End Function

Other solution maybe is replacing comma with dot in string and then passing it back to textbox.

If TextBox13.Text.Contains(",") Then
dim tempStr as string = TextBox13.Text
TextBox13.Text = Replace(tempStr, ",", ".")
dim test as double textbox1.text
msgbox(test)
End If

And anyway shouldn't this be written this way:

TextBox13.Text = tempStr.Replace(",", ".")

Upvotes: 1

Twiebie
Twiebie

Reputation: 412

Have you tried to cast the string to decimal or double?

Dim test as Decimal = CDec(textbox1.Text) Or Dim test as Double= CDbl(textbox1.Text)

Upvotes: 0

Related Questions