Search code examples
vb.netintegerarithmetic-expressions

Division arithmetic in VB.net automatically rounding off


I have a bit of an issue with the following piece of code.

        Dim k As Integer

    k = (TextBox1.Text - 750) \ 250

    MsgBox("There should be " & k & " items")

Lets say that textbox1 has a value of 3050 the outcome would be 9.20 however my Mesagebox returns 9 which is not what I want. In fact, I want to see it without the rounding off

How do I do that?


Solution

  • \ is integer division in VB, so you need to use / instead.

    See here (MSDN Documentation) for more information on VB operators.

    Also, as is mentioned in the comments, you're storing k as an integer - use double (or whatever) instead.

    So, how about:

    Dim k As Double
    Dim tbText as Double
    If Double.TryParse(TextBox1.Text, tbText) Then
        k = (tbText  - 750) / 250
    
        MsgBox("There should be " & k & " items")
    End If
    

    If you're certain that TextBox1.Text will be a number, you don't have to use TryParseit like I did - but I don't think you should ever trust a user to get it right...