How to sum integers from a string splitted with " - " in a rtb multiline

Mattia Fanti 356 Reputation points
2022-02-21T20:29:43.747+00:00

Hi, I'm parsing integers that are formatted like integer1 - integer2
like the following image

176527-immagine-2022-02-21-202828.jpg

Since I'm already asking how to format in a human readable integer the integer2 ( quantities) in this question

I would like to sum the integers( already formatted with k or M or B) in the Quantity side.
Also if possible, It would be really helpful if you can suggest me I can sum the quantity in each rtb like the following:

sum the quantities from the price 0.00000999 to 0.00001059

Hope it would be possible.
Many thanks

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,714 questions
0 comments No comments
{count} votes

Accepted answer
  1. LesHay 7,126 Reputation points
    2022-02-22T17:40:01.597+00:00

    Hi
    Try this version. Button2 needs to be added which is to recalculate values.

    Designer
    176936-111.png

    Code

    Option Strict On  
    Option Explicit On  
    Imports System.Net.Http  
    Imports System.Runtime.InteropServices  
    Imports System.Text  
    Imports Newtonsoft.Json  
      
    Public Class Form1  
      Dim currASKS As String()()  
      Dim currBIDS As String()()  
      
      <DllImport("user32.dll", CharSet:=CharSet.Auto)>  
      Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr  
      End Function  
      
      Private Const WM_VSCROLL As Integer = 277  
      Private Const SB_PAGEBOTTOM As Integer = 7  
      Friend Shared Sub ScrollToBottom(ByVal richTextBox As RichTextBox)  
        SendMessage(richTextBox.Handle, WM_VSCROLL, CType(SB_PAGEBOTTOM, IntPtr), IntPtr.Zero)  
        richTextBox.SelectionStart = richTextBox.Text.Length  
      End Sub  
      Public Class Result  
        Public Property asks As String()()  
        Public Property bids As String()()  
        Public Property seqNum As Integer  
        Public Property prevSeqNum As Integer  
        Public Property lastTs As Double  
      End Class  
      Public Class Root  
        Public Property [error] As Object  
        Public Property result As Result  
        Public Property id As Integer  
      End Class  
      Private URI As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=150&interval=1e-8"  
      
      Private Async Function GetJsonFromApi() As Task(Of Root)  
      
        Using http As New HttpClient(),  
                      response As HttpResponseMessage = Await http.GetAsync(URI)  
      
          Return JsonConvert.DeserializeObject(Of Root)(Await response.Content.ReadAsStringAsync())  
        End Using  
      End Function  
      
      Private Sub OutputAsks(asks As String()())  
        'asks  
        Try  
          Dim contents As New StringBuilder  
          currASKS = asks  
          ReCalcASKS()  
      
          For Each ask() As String In asks  
            contents.AppendLine(String.Join(" - ", {ask(0), ToKMB(GetDouble(ask(1)))}))  
          Next  
      
          RichTextBox1.BeginInvoke(Sub()  
                                     RichTextBox1.Text = contents.ToString()  
                                     RichTextBox1.Lines = RichTextBox1.Lines.  
                    Where(Function(x) Not String.IsNullOrEmpty(x)).  
                    OrderByDescending(Function(x) Decimal.Parse(x.Split(" "c)(0))).ToArray  
                                     ScrollToBottom(RichTextBox1)  
                                   End Sub)  
        Catch ex As Exception  
          MessageBox.Show("ERROR in asks")  
        End Try  
      End Sub  
      Private Sub OutputBids(bids As String()())  
        'bids  
        Try  
          Dim contents As New StringBuilder  
          currBIDS = bids  
          ReCalcBIDS()  
      
          For Each Bid() As String In bids  
            contents.AppendLine(String.Join(" - ", {Bid(0), ToKMB(GetDouble(Bid(1)))}))  
          Next  
      
          RichTextBox2.BeginInvoke(Sub()  
                                     RichTextBox2.Text = contents.ToString()  
                                   End Sub)  
        Catch ex As Exception  
          MessageBox.Show("ERROR in Bids")  
        End Try  
      End Sub  
      Public Shared Function ToKMB(num As Double) As String  
        If num > 999999999 OrElse num < -999999999 Then  
          Return num.ToString("0,,,.###B", Globalization.CultureInfo.InvariantCulture)  
        ElseIf num > 999999 OrElse num < -999999 Then  
          Return num.ToString("0,,.##M", Globalization.CultureInfo.InvariantCulture)  
        ElseIf num > 999 OrElse num < -999 Then  
          Return num.ToString("0,.#K", Globalization.CultureInfo.InvariantCulture)  
        Else  
          Return num.ToString("#.00", Globalization.CultureInfo.InvariantCulture)  
        End If  
      End Function  
      Function GetDouble(s As String) As Double  
        Dim v As Double = 0.0D  
        If Double.TryParse(s, v) Then Return v  
        Return 0.0D  
      End Function  
      Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick  
        Dim root As Root = Await GetJsonFromApi()  
        OutputAsks(root.result.asks)  
        OutputBids(root.result.bids)  
      
        ' change to a 5 second interval  
        Timer1.Interval = 5000  
      End Sub  
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
        Timer1.Start()  
      End Sub  
      Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
        ReCalcASKS()  
        ReCalcASKS()  
      End Sub  
      Sub ReCalcASKS()  
        Label1.Text = ToKMB(Calc(currASKS, GetDouble(TextBox1.Text), GetDouble(TextBox2.Text)))  
      End Sub  
      Sub ReCalcBIDS()  
        Label2.Text = ToKMB(Calc(currBIDS, GetDouble(TextBox3.Text), GetDouble(TextBox4.Text)))  
      End Sub  
      Function Calc(lst As String()(), min As Double, max As Double) As Double  
        If lst Is Nothing Then Return 0  
        Dim sum As Double  
        For Each s As String() In lst  
          Dim a As Double = GetDouble(s(0))  
          Dim b As Double = GetDouble(s(1))  
          If a >= min AndAlso a <= max Then sum += b  
        Next  
        Return sum  
      End Function  
      
    End Class  
    

5 additional answers

Sort by: Most helpful
  1. LesHay 7,126 Reputation points
    2022-02-22T01:21:39.43+00:00

    Hi
    Here is the code from the other question with a couple of labels added and code to sum the Integer parts of each set of data. I feel that maybe it isn't what you want though. Not sure of the other part of the question.

    Option Strict On
    Option Explicit On
    Imports System.Net.Http
    Imports System.Runtime.InteropServices
    Imports System.Text
    Imports Newtonsoft.Json
    
    Public Class Form1
      <DllImport("user32.dll", CharSet:=CharSet.Auto)>
      Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
      End Function
    
      Private Const WM_VSCROLL As Integer = 277
      Private Const SB_PAGEBOTTOM As Integer = 7
      Friend Shared Sub ScrollToBottom(ByVal richTextBox As RichTextBox)
        SendMessage(richTextBox.Handle, WM_VSCROLL, CType(SB_PAGEBOTTOM, IntPtr), IntPtr.Zero)
        richTextBox.SelectionStart = richTextBox.Text.Length
      End Sub
      Public Class Result
        Public Property asks As String()()
        Public Property bids As String()()
        Public Property seqNum As Integer
        Public Property prevSeqNum As Integer
        Public Property lastTs As Double
      End Class
      Public Class Root
        Public Property [error] As Object
        Public Property result As Result
        Public Property id As Integer
      End Class
      Private URI As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=150&interval=1e-8"
    
      Private Async Function GetJsonFromApi() As Task(Of Root)
    
        Using http As New HttpClient(),
                      response As HttpResponseMessage = Await http.GetAsync(URI)
    
          Return JsonConvert.DeserializeObject(Of Root)(Await response.Content.ReadAsStringAsync())
        End Using
      End Function
      Private Sub OutputAsks(asks As String()())
        'asks
        Try
          Dim contents As New StringBuilder
          Dim sum As Integer = 0
          For Each ask() As String In asks
    
            Dim i As Integer = GetInteger(ask(1))
            sum += i
            contents.AppendLine(String.Join(" - ", {ask(0), ToKMB(i)}))
          Next
          Label1.Text = ToKMB(sum)
    
          RichTextBox1.BeginInvoke(Sub()
                                     RichTextBox1.Text = contents.ToString()
                                     RichTextBox1.Lines = RichTextBox1.Lines.
                    Where(Function(x) Not String.IsNullOrEmpty(x)).
                    OrderByDescending(Function(x) Decimal.Parse(x.Split(" "c)(0))).ToArray
                                     ScrollToBottom(RichTextBox1)
                                   End Sub)
        Catch ex As Exception
          MessageBox.Show("ERROR in asks")
        End Try
      End Sub
      Private Sub OutputBids(bids As String()())
        'bids
        Try
          Dim contents As New StringBuilder
          Dim sum As Integer = 0
          For Each Bid() As String In bids
            Dim i As Integer = GetInteger(Bid(1))
            sum += i
            contents.AppendLine(String.Join(" - ", {Bid(0), ToKMB(i)}))
          Next
          Label2.Text = ToKMB(sum)
    
          RichTextBox2.BeginInvoke(Sub()
                                     RichTextBox2.Text = contents.ToString()
                                   End Sub)
        Catch ex As Exception
          MessageBox.Show("ERROR in Bids")
        End Try
      End Sub
      Public Shared Function ToKMB(num As Integer) As String
        If num > 999999999 OrElse num < -999999999 Then
          Return num.ToString("0,,,.###B", Globalization.CultureInfo.InvariantCulture)
        ElseIf num > 999999 OrElse num < -999999 Then
          Return num.ToString("0,,.##M", Globalization.CultureInfo.InvariantCulture)
        ElseIf num > 999 OrElse num < -999 Then
          Return num.ToString("0,.#K", Globalization.CultureInfo.InvariantCulture)
        Else
          Return num.ToString("#.00", Globalization.CultureInfo.InvariantCulture)
        End If
      End Function
      Function GetInteger(s As String) As Integer
        Dim v As Integer = 0
        If Integer.TryParse(s, v) Then Return v
        Return 0
      End Function
      Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Dim root As Root = Await GetJsonFromApi()
        OutputAsks(root.result.asks)
        OutputBids(root.result.bids)
    
        ' only one pass for this test
        Timer1.Stop()
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Timer1.Start()
      End Sub
    End Class
    
    1 person found this answer helpful.

  2. LesHay 7,126 Reputation points
    2022-02-22T15:18:47.91+00:00

    Hi
    You need to think more carefully when making a question, just as you would need to do when writing code. You say 'Can we calculate the sum of the integers between these prices range? ', and you do not state that either of the minimum or maximum of the range are to be included - this means they must be excluded as 'between' infers. If that is not what you meant then you will need to edit the code below to reflect that.
    This code has 2 textboxes, 1 for min 1 for max, 2 labels, 1 for calc total in LB1 and 1 for calc total in LB2 (both expressed in terms of TuKMB), and both 'between' the min and max. However, it would seem that LB2 doesn't contain any items that fall into the min/max range.
    Again, the ideas here might be of use to you if you edit according to your needs.

    176857-111.png

    Option Strict On  
    Option Explicit On  
    Imports System.Net.Http  
    Imports System.Runtime.InteropServices  
    Imports System.Text  
    Imports Newtonsoft.Json  
      
    Public Class Form1  
      Dim min As Double = 0D  
      Dim max As Double = 0D  
      
      <DllImport("user32.dll", CharSet:=CharSet.Auto)>  
      Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr  
      End Function  
      
      Private Const WM_VSCROLL As Integer = 277  
      Private Const SB_PAGEBOTTOM As Integer = 7  
      Friend Shared Sub ScrollToBottom(ByVal richTextBox As RichTextBox)  
        SendMessage(richTextBox.Handle, WM_VSCROLL, CType(SB_PAGEBOTTOM, IntPtr), IntPtr.Zero)  
        richTextBox.SelectionStart = richTextBox.Text.Length  
      End Sub  
      Public Class Result  
        Public Property asks As String()()  
        Public Property bids As String()()  
        Public Property seqNum As Integer  
        Public Property prevSeqNum As Integer  
        Public Property lastTs As Double  
      End Class  
      Public Class Root  
        Public Property [error] As Object  
        Public Property result As Result  
        Public Property id As Integer  
      End Class  
      Private URI As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=150&interval=1e-8"  
      
      Private Async Function GetJsonFromApi() As Task(Of Root)  
      
        Using http As New HttpClient(),  
                      response As HttpResponseMessage = Await http.GetAsync(URI)  
      
          Return JsonConvert.DeserializeObject(Of Root)(Await response.Content.ReadAsStringAsync())  
        End Using  
      End Function  
      Private Sub OutputAsks(asks As String()())  
        'asks  
        Try  
          Dim contents As New StringBuilder  
          Dim sum As Double = 0D  
          min = GetDouble(TextBox1.Text)  
          max = GetDouble(TextBox2.Text)  
          For Each ask() As String In asks  
            Dim a As Double = GetDouble(ask(0))  
            Dim b As Double = GetDouble(ask(1))  
            If a > min AndAlso a < b Then sum += b  
            contents.AppendLine(String.Join(" - ", {ask(0), ToKMB(b)}))  
          Next  
          Label1.Text = ToKMB(sum)  
      
          RichTextBox1.BeginInvoke(Sub()  
                                     RichTextBox1.Text = contents.ToString()  
                                     RichTextBox1.Lines = RichTextBox1.Lines.  
                    Where(Function(x) Not String.IsNullOrEmpty(x)).  
                    OrderByDescending(Function(x) Decimal.Parse(x.Split(" "c)(0))).ToArray  
                                     ScrollToBottom(RichTextBox1)  
                                   End Sub)  
        Catch ex As Exception  
          MessageBox.Show("ERROR in asks")  
        End Try  
      End Sub  
      Private Sub OutputBids(bids As String()())  
        'bids  
        Try  
          Dim contents As New StringBuilder  
          Dim sum As Double = 0D  
          min = GetDouble(TextBox1.Text)  
          max = GetDouble(TextBox2.Text)  
          For Each Bid() As String In bids  
            Dim a As Double = GetDouble(Bid(0))  
            Dim b As Double = GetDouble(Bid(1))  
            If a > min AndAlso a < b Then sum += b  
            contents.AppendLine(String.Join(" - ", {Bid(0), ToKMB(b)}))  
          Next  
          Label2.Text = ToKMB(sum)  
      
          RichTextBox2.BeginInvoke(Sub()  
                                     RichTextBox2.Text = contents.ToString()  
                                   End Sub)  
        Catch ex As Exception  
          MessageBox.Show("ERROR in Bids")  
        End Try  
      End Sub  
      Public Shared Function ToKMB(num As Double) As String  
        If num > 999999999 OrElse num < -999999999 Then  
          Return num.ToString("0,,,.###B", Globalization.CultureInfo.InvariantCulture)  
        ElseIf num > 999999 OrElse num < -999999 Then  
          Return num.ToString("0,,.##M", Globalization.CultureInfo.InvariantCulture)  
        ElseIf num > 999 OrElse num < -999 Then  
          Return num.ToString("0,.#K", Globalization.CultureInfo.InvariantCulture)  
        Else  
          Return num.ToString("#.00", Globalization.CultureInfo.InvariantCulture)  
        End If  
      End Function  
      Function GetDouble(s As String) As Double  
        Dim v As Double = 0.0D  
        If Double.TryParse(s, v) Then Return v  
        Return 0.0D  
      End Function  
      Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick  
        Dim root As Root = Await GetJsonFromApi()  
        OutputAsks(root.result.asks)  
        OutputBids(root.result.bids)  
      
        ' only one pass for this test  
        Timer1.Stop()  
      End Sub  
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
        Timer1.Start()  
      End Sub  
    End Class  
    
    1 person found this answer helpful.
    0 comments No comments

  3. LesHay 7,126 Reputation points
    2022-02-21T20:41:07.327+00:00

    Hi

    One suggestion. Throughout your code, keep the numeric values as pure numbers and not strings. Then when you want to display them, perhaps the results of calculations etc, then convert to a string.
    I think (if I understand correctly) that you are taking a number, changing it to a string then wanting to use it in a calculation (which means it needs to be converted back to a number).

    If, on the other hand, you are dealing with strings right from the start, then my suggestion would be to convert them to numeric values, use them throughout your code and change results etc back to strings only when needed for display.

    If I have misunderstood, just ignore this.

    0 comments No comments

  4. LesHay 7,126 Reputation points
    2022-02-22T16:04:15.857+00:00

    Hi
    Please do not assume I know what you are thinking! You must explain and be explicit in any question.
    What does 'when I'm goint to set a prices range, it seems it's not considering the first line range' mean?

    Yes, you can do the calculation on a Button click, but I am not going to do it for you. It is your application and for you to do something.

    You make no mention of the point I raised in my last post about inclusive/exclusive values - do you not consider answering my points as much as you want me to answer your points?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.