簡體   English   中英

文本框中的自動小數位

[英]Automatic decimal places in textbox

看起來很奇怪,但是找不到我的問題的在線解決方案! 至少在VB.NET中。

達成協議:我有一個格式為TextBox的文本框(受KeyPress事件限制為數字),並且只要用戶輸入其數據,便希望保留兩位小數。

例如,如果文本框為空白,則當用戶按下時,假設“ 2”,則文本框顯示為“ 0,02”。 然后,如果用戶按下“ 7”,則文本框將顯示“ 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.我來自葡萄牙,在這里我們使用逗號(“,”)代替小數點分隔符(“。”)。

您能幫我調整一下代碼,使其小數點后兩位有效嗎?

任何幫助將不勝感激。 並且,一如既往,謝謝大家。

這是我制作的自定義類,可以滿足您的要求:

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 31748.0 => 31748.0 / 10 2 = 317.48 )。

  • 最后,它以格式為0.x的十進制調用ToString() -其中x是重復的零,具體取決於所需的小數位數(例如2個小數 => 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

希望這可以幫助!

謝謝@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

這段代碼對我來說看起來可疑簡單。 現在,它可以正常工作,並且完全按照我的意願進行操作。 也許我缺少一些東西,或者我對目標的描述還不夠清楚。 如果您發現我的方法有任何缺陷,請隨時指出! 我會非常感激。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM