Home > Net >  How to remove characters next to integers in richtextbox multiline and sum them
How to remove characters next to integers in richtextbox multiline and sum them

Time:01-14

I'm trying to find for a character in my richtextbox multiline and I want to sum the integers next to them. I'm looking for the character "M" like the follow:

68.9M

4.13M

5.05M

Removing the M and trying to make a sum of them, but it just removing the M without showing any messaagebox with the sum. This is the code I'm working with:

Dim sum As Integer = 0
            RichTextBox1.Text = RichTextBox1.Text.Replace("M", "")
            For Each s As String In RichTextBox1.Lines
                Dim num As Integer = 0
                If Integer.TryParse(s, num) Then
                    sum  = num
                    MsgBox(sum)
                End If
            Next

What I'm doing wrong? Thanks

CodePudding user response:

Since I'm operating with doubles, decimals or float (Single) values, Integer.TryParse() will fail the test. Also, my current Culture uses a dot as thousands separator.

So the right code is the following, making sure to use the MessageBox outside of the loop:

Dim sum As Double = 0
RichTextBox1.Text = RichTextBox1.Text.Replace("M", "")

For Each s As String In RichTextBox1.Lines
    Dim num As Double = 0
    If Double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, num) Then
        sum  = num
    End If
Next
MsgBox(sum)
  •  Tags:  
  • Related