文本框中的自动小数位

时间:2017-07-03 14:12:11

标签: vb.net textbox decimal

看起来很奇怪,但我无法找到解决问题的在线解决方案!至少在VB.NET中。

以下是这笔交易: 我有一个表单中的TextBox(仅限于KeyPress事件的数字),并且只要用户输入他的数据,就想保留两个小数位。

例如,如果TextBox为空白,那么,当用户按下时,让我们说," 2",TextBox显示" 0,02"。然后,如果用户按下" 7",则TextBox显示" 0,27"。然后再次按下" 6",它显示" 2,76"等等...

我设法用一个小数位来执行此操作,代码为:

    Select Case Me.TextBox.Text
        Case ""
        Case ","
            Me.TextBox.Text = ""
        Case Else
            Me.TextBox.Text = Strings.Left(Replace(Me.TextBox.Text, ",", ""), Strings.Len(Replace(Me.TextBox.Text, ",", "")) - 1) & "," & Strings.Right(Replace(Me.TextBox.Text, ",", ""), 1)
            Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
    End Select

请注意: 1。此代码在TextChanged事件中运行; 2。我来自葡萄牙,在这里我们使用逗号(",")代替点("。")小数分隔符。

你能帮我调整一段代码,以便用两位小数来正常工作吗?

任何帮助将非常感谢。并且,一如既往地提前感谢你们。

2 个答案:

答案 0 :(得分:3)

这是我制作的自定义课程,可以满足您的需求:

Public Class FactorDecimal
    Private _value As String = "0"

    Public DecimalPlaces As Integer

    Public Sub AppendNumber(ByVal Character As Char)
        If Char.IsNumber(Character) = False Then Throw New ArgumentException("Input must be a valid numerical character!", "Character")
        _value = (_value & Character).TrimStart("0"c)
    End Sub

    Public Sub RemoveRange(ByVal Index As Integer, ByVal Length As Integer)
        If _value.Length >= Me.DecimalPlaces + 1 AndAlso _
            Index + Length > _value.Length - Me.DecimalPlaces Then Length -= 1 'Exclude decimal point.

        If Index + Length >= _value.Length Then Length = _value.Length - Index 'Out of range checking.

        _value = _value.Remove(Index, Length)

        If _value.Length = 0 Then _value = "0"
    End Sub

    Public Overrides Function ToString() As String
        Dim Result As Decimal
        If Decimal.TryParse(_value, Result) = True Then
            'Divide Result by (10 ^ DecimalPlaces) in order to get the amount of decimal places we want.
            'For example: 2 decimal places   =>   Result / (10 ^ 2) = Result / 100 = x,xx.
            Return (Result / (10 ^ Me.DecimalPlaces)).ToString("0." & New String("0"c, Me.DecimalPlaces))
        End If
        Return "<parse error>"
    End Function

    Public Sub New(ByVal DecimalPlaces As Integer)
        If DecimalPlaces <= 0 Then DecimalPlaces = 1
        Me.DecimalPlaces = DecimalPlaces
    End Sub
End Class

它可以让你附加数字来形成一长串数字字符(例如3174 + 8 = 31748),然后当你调用ToString()时执行以下操作:

  • 它将长号字符串解析为小数(例如"31748" => 31748.0

  • 它将小数乘以10加到你想要的小数位数(例如: 2小数 =&gt; 31748.0 / 102 = 317.48)。

  • 最后,它使用格式为ToString()的小数点调用0.x - 其中x是重复的零值,具体取决于您想要的小数位数(例如 2位小数 =&gt; 0.00)。

注意:此解决方案适应当前系统的文化设置,因此将自动使用该文化中定义的小数点。例如,在美国(en-US)系统中,它将使用点:317.48,而在瑞典语(sv-SE)或葡萄牙语(pt-PT)系统中,它将使用逗号:317,48

你可以像这样使用它:

Dim FactorDecimal1 As New FactorDecimal(2)

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    If Char.IsNumber(e.KeyChar) = False Then
        e.Handled = True 'Input was not a number.
        Return
    End If

    FactorDecimal1.AppendNumber(e.KeyChar)
    TextBox1.Text = FactorDecimal1.ToString()
End Sub

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
    Dim TargetTextBox As TextBox = DirectCast(sender, TextBox)
    e.SuppressKeyPress = True

    Select Case e.KeyData 'In order to not block some standard keyboard shortcuts (ignoring paste since the pasted text won't get verified).
        Case Keys.Control Or Keys.C
            TargetTextBox.Copy()
        Case Keys.Control Or Keys.X
            TargetTextBox.Cut()
        Case Keys.Control Or Keys.A
            TargetTextBox.SelectAll()
        Case Keys.Back, Keys.Delete 'Backspace or DEL.
            FactorDecimal1.RemoveRange(TextBox1.SelectionStart, If(TextBox1.SelectionLength = 0, 1, TextBox1.SelectionLength))
            TextBox1.Text = FactorDecimal1.ToString()
        Case Else
            e.SuppressKeyPress = False 'Allow all other key presses to be passed on to the KeyPress event.
    End Select
End Sub

在线测试: http://ideone.com/fMcKJr

希望这有帮助!

答案 1 :(得分:1)

谢谢@Visual Vincent。你的方法很好。但是我设法通过以下代码找到了一种更简单的方法:

Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox.KeyPress
    If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
        e.Handled = True
    End If
End Sub
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox.TextChanged
    Select Case Val(Replace(Me.TextBox.Text, ",", "."))
        Case 0 : Me.TextBox.Text = ""
        Case Else
            Me.TextBox.Text = Format(Val(Replace(Me.TextBox.Text, ",", "")) / 100, "0.00")
            Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
    End Select
End Sub

这段代码对我来说很简单。现在它工作正常,并按照我想要的方式完成诀窍。也许我不知道有什么东西,或者说我对目标的描述还不够清楚。 如果您发现我的方法存在任何缺陷,请随时指出!我非常感激。