-1

I'm having to create a random math generator in visual basic, when a user selects divide it should show the number to the second decimal. Anything I have tried so far keeps rounding off. option strict on is required

this is the code I have so far

Private Sub DivisionProblem()
    ' Divide two numbers and display the answer
    Dim numSmallestNum As Integer = CreateANumber()
    Dim numLargestNum As Integer = CreateANumber()
    Dim strToWork As String


    If (numLargestNum > numSmallestNum) Then
        strToWork = (Convert.ToString(numLargestNum) & " / " & Convert.ToString(numSmallestNum))
        lblToWork.Text = strToWork

        _decAnswer = CInt((Decimal.Round(CDec(numLargestNum / numSmallestNum), 2)))

    Else
        strToWork = (numSmallestNum & " / " & numLargestNum)
        lblToWork.Text = strToWork
        _decAnswer = CInt((Decimal.Round(CDec(numSmallestNum / numLargestNum), 2)))
    End If
End Sub

if anyone has any suggestions I would greatly appreciate it. thank you!

  • 1
    `_decAnswer` is not a legal VBA identifier. And `CInt` converts to `Integer`, which is, well, an *integer* data type. And `Option Strict` is a VB.NET thing - VBA and VB.NET are completely different things. Start by removing `Imports Microsoft.VisualBasic` from your modules if you want to write idiomatic .net code. – Mathieu Guindon Apr 27 '17 at 21:25
  • 1
    Possible duplicate of [VB CStr, CDate, CBool, etc. vs. DirectCast for casting without conversion](http://stackoverflow.com/questions/1379537/vb-cstr-cdate-cbool-etc-vs-directcast-for-casting-without-conversion) – Mathieu Guindon Apr 27 '17 at 21:28

4 Answers4

3

CInt forces the value to be of Integer not Double.

Doug Coats
  • 6,255
  • 9
  • 27
  • 49
2
Dim numSmallestNum As Integer = CreateANumber()
Dim numLargestNum As Integer = CreateANumber()

Declare these two As Decimal and there's no need to convert anything.

Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235
1

You'll want to Dim _decAnswer as Decimal and use CDec instead of CInt.

For additional context on the Decimal type, check out this article

You might also want to consider using Double and CDbl instead of Decimal and CDec, depending on your use case.

airstrike
  • 2,270
  • 1
  • 25
  • 26
0

Well as far as I know an Integer does not save decimals. Use Dim ... As Decimal. Just make life easier

TGamer
  • 529
  • 1
  • 9
  • 26