简体   繁体   中英

Ignoring decimals in VB

I have only started programming in VB recently and I am not very good on the coding side. Could somebody help me with the following problem?

I have two values a and b . When I divide them, I want only the integer part to show up ignoring all the decimals and storing it into the variable c

ie

a = 24, b = 11
c = 2

output: 2

If a, b, and c are ints it will do this automatically. Alternatively, if none of the values are ints you can just cast the result to int:

c = Convert.ToInt32(a / b)

EDIT: To convert from strings you can just say:

Dim c as Int32 = Convert.ToInt32(a) / Convert.ToInt32(b)

This will throw an exception if the strings passed in aren't ints. If you're expecting to get invalid ints you can use the TryCast operator or TryParse method which will return nothing rather than throwing an exception.

Dim intA as Int32 = Int32.TryParse(a)
Dim intB as Int32 = Int32.TryParse(b)
Dim intC as Int32

If (intA IsNot Nothing) And (intB IsNot Nothing) Then
    intC = intA / intB
Else
    'Strings couldn't be converted
End If

I would also advise you to put in something preventing divide by zero, unless you just want an exception to be thrown.

Based on your comment, here's how you could do it if a and b were strings:

Sub Main
    Dim a = "24" , b = "11"
    Dim c as Integer = CInt(a) / CInt(b)
    Console.WriteLine(c)
End Sub

And if c has to be a string...

Sub Main
    Dim a = "24" , b = "11"
    Dim c = CInt((CInt(a) / CInt(b))).ToString()
    Console.WriteLine(c)
End Sub

I'm more of a C# person, so there may be an easier way.

UPDATE To handle rounding, you could do it this way:

Sub Main
    Dim a = "24" , b = "5"
    Dim c = Math.Round(CInt(a) / CInt(b)).ToString()
    Console.WriteLine(c)
End Sub

I've skipped getting strings into numbers, since that's a separate issue from your primary question of ignorning decimals.

Assuming you have integers a and b , you can either do:

Dim c = CInt(a / b) 'Will round decimal answer
Dim c = CInt(Int(a / b)) 'Will truncate decimal

CInt and ConvertToInt32 both do rounding (to the nearest even integer when the fractional value is 0.5).

Instead of the Int function, you could use Fix which has different behavior for negative numbers. Also available to you is Math.Floor which again has specific behavior regarding negative number you'll want to be aware of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM