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
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
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.
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.
Related
in Vb.net how to get the number after decimal places.
I tried below code.
Dim number As Decimal = 143.500
Dim wholePart As Integer = Decimal.Truncate(number)
Dim fractionPart As Decimal = number - wholePart
Dim secondPart3 As Integer
secondPart3 = Replace(fractionPart, "0.", "0")
then the result is coming 500, but when i tried 143.050 its giving 50 it should show 050
Thanks
Thanks everyone. i got it with sample below code
Dim numar As Double
If Double.TryParse(TextBox1.Text, numar) Then
Dim rmndr As Double
rmndr = numar Mod 1
If rmndr = 0 Then
Else
TextBox2.Text = Split(CStr(TextBox1.Text), ".")(1)
End If
End If
Your solution (here) is unnecessarily complex. You were on the right track in your original post, but conflated numeric values with formatted string values. Because while 050 are 50 are the same numeric value, when you implicitly call ToString on the value (or explicitly with the wrong formatting) then you would always get 50 because the prefixing 0 is unnecessary when working with numeric values.
What you should do is:
Get the integral digits of the decimal value
Convert the underlying decimal value to a String
(optionally) Format the String specifying the level of precision
Drop the integral digits off converted string
Here is an example:
Private Function GetFractionalDigits(value As Decimal) As String
Dim integralDigits = Decimal.Truncate(value)
Return value.ToString().Remove(0, integralDigits.ToString().Length + 1)
End Function
Private Function GetFractionalDigits(value As Decimal, precisionSpecifier As Integer) As String
If (precisionSpecifier < 0) Then
Throw New ArgumentOutOfRangeException("precisionSpecifier", "precisionSpecifier cannot be less than 0")
End If
Dim integralDigits = Decimal.Truncate(value)
Return value.ToString("N" & precisionSpecifier).Remove(0, integralDigits.ToString().Length + 1)
End Function
Fiddle: https://dotnetfiddle.net/SBOXG0
May I know got any simple way to perform this? It will hit an error when a.text is null. If I don't detect one by one, With a simple code may I convert a.text null to 0?
Dim count1 As Integer = 0
count1 = Convert.ToInt32(a.Text) + Convert.ToInt32(b.Text) + Convert.ToInt32(c.Text)
txt_display.Text = count1
Got any other method rather that I do like below detect one by one.
if a.Text = "" Then
a.Text = 0
End If
You have to detect one by one. Better way, will be to create your own function. Try below.
Dim count1 As Integer = 0
count1 = ConvertToInteger(a.Text) + ConvertToInteger(b.Text) + ConvertToInteger(c.Text)
txt_display.Text = count1
Private Function ConvertToInteger(ByRef value As String) As Integer
If String.IsNullOrEmpty(value) Then
value = "0"
End If
Return Convert.ToInt32(value)
End Function
If your objective is to sum the values in your textboxes and ignore the textboxes that cannot be converted to integers then you can simply use Int32.TryParse.
It will set your variable to 0 if the text cannot be converted to an integer without throwing exceptions.
' In place of your textboxes
Dim x1 As String = "2"
Dim x2 As String = Nothing
Dim x3 As String = "5"
Dim a, b, c As Integer
Int32.TryParse(x1, a)
Int32.TryParse(x2, b)
Int32.TryParse(x3, c)
Dim result = a + b + c
Console.WriteLine(result)
Instead, if you want to write the "0" string into the textbox text to signal your user of the wrong input, then you have to check the textboxes one by one, again using Int32.TryParse
Dim value1 as Integer
if Not Int32.TryParse(a.Text, value1) Then
a.Text = "0"
End If
' Here the variable value1 contains the converted value or zero.
' repeat for the other textboxes involved
A different approach using If Operator:
Dim count1 As Integer = 0
count1 = If(String.IsNullOrEmpty(a.Text), 0, Convert.ToInt32(a.Text)) + If(String.IsNullOrEmpty(b.Text), 0, Convert.ToInt32(b.Text)) + If(String.IsNullOrEmpty(c.Text), 0, Convert.ToInt32(c.Text))
txt_display.Text = count1
Example:
If String.IsNullOrEmpty(a.Text) Then
a.Text = "0"
End If
As per the Microsoft Documentation, a null string (Nothing) is different from an empty string (""):
The default value of String is Nothing (a null reference). Note that this is not the same as the empty string (value "").
You also use the = operator, which can be tricky with String types. For more info, see this post and the answer which was awarded a 50 points bounty.
If you use If with only two arguments, the following code
If a.Text Is Nothing Then
a.Text = 0
End If
Can be turned into a one-liner: Dim MyNumber as Integer = If(a.Text, 0)
If you meant to work with empty strings, then you can use: Dim MyNumber as Integer = If(a.Text.Length = 0, 0, a.Text).
If you want to deal with both, you can use String.IsNullOrEmpty(a.Text) as suggested by the currently accepted answer; or you can use a.Text="", a.Text = String.Empty, or a.Text = vbNullString, which are all equal (see the post I referred to earlier)
Finally, note that the conversion from a String type to an Integer type is made implicitly. There is no need to use the explicit cast conversions such as CType() or Convert.ToInt32.
both txtfield1 and txtMCLCCurrToEUR are doubles
(originally strings converted to double, both are the values of forex with 5 digits after decimal point)
Dim f1 As Double
txtField2.Text = (Double.TryParse(txtMCLCurrToEUR.Text, f1) / Double.TryParse(txtField1.Text, f1)).ToString("N5")
irrespective of their values, I always end up with 1 in the txtField2.text
I seem to have overlooked something essential, but for the life of me -- I don't see what it could be...
any help would be much appreciated!
You should not use f1 for both conversions, the second one would overwrite the first and the result is always one.
Tryparse has no return value, only a flac vor succeed or not.
Dim f1 As Double
Double.TryParse(txtMCLCurrToEUR.Text, f1)
Dim f2 As Double
Double.TryParse(txtField1.Text, f2)
txtField2.Text = (f1/f2 ).ToString("N5")
Double.TryParse() will return a Boolean value(true/false), true for success and false in case of failure of conversion from string to double. so that if you apply division over Boolean values it will gives you result as either 1 or 0.
You can realize this by running your program by enabling Option Strict On
consider one example:
Dim a = True
Dim b = True
Dim c = CDbl(a) / CDbl(b) ' will gives you output as 1
Where as
Dim a = True
Dim b = False
Dim c = CDbl(a) / CDbl(b) ' will gives you output as -1.#INF
Simply you can do this without using any third variable, like the following.
txtField2.Text = (Val(txtMCLCurrToEUR.Text) / Val(txtField1.Text)).ToString("N5")
Val() will return 0 in case it failed to convert the input string/null
how can i check if a string only contains 4 digit numbers ( or a year )
i tried this
Dim rgx As New Regex("^/d{4}")
Dim number As String = "0000"
Console.WriteLine(rgx.IsMatch(number)) // true
number = "000a"
Console.WriteLine(rgx.IsMatch(number)) // false
number = "000"
Console.WriteLine(rgx.IsMatch(number)) //false
number = "00000"
Console.WriteLine(rgx.IsMatch(number)) // true <<< :(
this returns false when its less than 4 or at characters but not at more than 4
thanks!
I actually wouldn't use a regex for this. The expression is deceptively simple (^\d{4}$), until you realize that you also need to evaluate that numeric value to determine a valid year range... unless you want years like 0013 or 9015. You're most likely going to want the value as an integer in the end, anyway. Given that, the best validation is probably just to actually try to convert it to an integer right off the bat:
Dim numbers() As String = {"0000", "000a", "000", "00000"}
For Each number As String In numbers
Dim n As Integer
If Integer.TryParse(number, n) AndAlso number.Length = 4 Then
'It's a number. Now look at other criteria
End If
Next
Use LINQ to check if All characters IsDigit:
Dim result As Boolean = ((Not number Is Nothing) AndAlso ((number.Length = 4) AndAlso number.All(Function(c) Char.IsDigit(c))))
You should use the .NET string manipulation functions.
Firstly the requirements, the string must:
Contain exactly four characters, no more, no less;
Must consist of a numeric value
However your aim is to validate a Date:
Function isKnownGoodDate(ByVal input As String) As Boolean 'Define the function and its return value.
Try 'Try..Catch statement (error handling). Means an input with a space (for example ` ` won't cause a crash)
If (IsNumeric(input)) Then 'Checks if the input is a number
If (input.Length = 4) Then
Dim MyDate As String = "#01/01/" + input + "#"
If (IsDate(MyDate)) Then
Return True
End If
End If
End If
Catch
Return False
End Try
End Function
You may experience a warning:
Function isKnownGoodDate does not return a value on all code
paths. Are you missing a Return statement?
this can be safely ignored.
I have got a text box that displays the result of two others multiplied together, before anything is in-putted the box displays NaN, is there a way to have it display "0" or even remain empty before anything multiplied.
Dim thick1 As Double
Dim tb8 As Double
Dim result As Double
thick1 = Val(thickness1.Text)
tb8 = Val(TextBox8.Text)
result = thick1 / tb8
TextBox30.Text = FormatNumber(result, 3)
^ the above code is what I am using for the text box.
Try something like this:
Dim result As Double
Dim thick1 As Double = CDbl(thickness1.Text)
Dim tb8 As Double = CDbl(TextBox8.Text)
If IsNumeric(thick1) AndAlso IsNumeric(tb8) AndAlso tb8 <> 0 Then
result = thick1 / tb8
TextBox30.Text = result.ToString("G3")
End If
Another way, try this:
TextBox30.Text = FormatNumber(result, 3).Tostring("n0")
I think it should displays a 0 even if number is not present (like a NaN string)
MSDN: The Numeric ("N") Format Specifier
If not, then try this else:
TextBox30.Text = FormatNumber(result, 3).ToString("0")
"0" Zero placeholder
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
MSDN: Custom Numeric Format Strings
This would appear to be code in an event or form load that it is automatically running. If the textboxes do not yet have values, then result = thick1 / tb8 will result in Nan (not a Number) because you cannot divide by zero.
Again, assuming an event or something:
If tb8 = 0 then
Exit Sub
else
result = thick1 / tb8
TextBox30.Text = result.ToString("G3")
End if
In addition to dumping VAL for TryParse, consider turning Option Explicit on