dividing 2 doubles results always in 1 vb - vb.net

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

Related

Vb.net how to get the number after decimal places

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

Convert String to integer and get null equal to 0

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.

How to get the count of digits after the comma of a double-number in VB.NET?

Examples:
Double-Number is 56.6789 result should be 4
Double-Number is 12345.67 result should be 2
Double-Number is 12345.6 result should be 1
I have a solution tinkering with strings, but I think there is an mathematical solution?
Please in VB.NET ...
Split the original number and get the length of the upper index (1)
myNumber = 12.3456
Dim count As Integer = Len(Split(CStr(myNumber), Application.DecimalSeparator)(1))
Debug.Print count // prints '4'
edit: replaced "." with decimal separator to ensure use across varying cultures
You can try like this:
Dim x As String = CStr(56.6789)
Dim count = x.Length - InStr(x, ".")
One way to do it is to keep knocking off the whole part, multiplying by 10, repeat until you have an integer:
Dim x As Double = 1.23456
Dim count As Integer = 0
While Math.Floor(x) <> x
x = (x - Math.Floor(x)) * 10D
count = count + 1
End While
Note this will fail if there is an infinite number of decimal places - so you could set a limit on it (If count > 100 Then Exit While)
Another way would be like this, which converts to a string but removes the need to hardcode the separator.
Dim x As Double = 1.23456
Dim x0 As Double = x - Math.Floor(x)
Dim x0String As String = x0.ToString()
Dim count As Integer = x0String.Substring(2, x0String.Length - 2).Length
Using Application.DecimalSeparator also allows a string to be used.
The method with a string will again lose information about an infinite-length fractional part, as it will truncate it.

How to multiply all the values of a column?

I've a DataGridView like this layout:
I would like to find a way to multiply all values of the column "Quota", in particular, I wrote a code like this:
If MetroGrid1.Rows.Count > 0 Then
If MetroGrid1.Columns.Contains("Quota") Then
Dim CostTotal As Decimal = MetroGrid1.Rows.Cast(Of DataGridViewRow) _
.Select(
Function(x)
Return CDec(x.Cells("Quota").Value)
End Function
).Sum
Dim risultato = CostTotal * giocata
The problem is that the only mode available is the sum and average, but there is no multiplication. I would like to find a way to replace .Sum with some command that allows me to multiply or totally change the algorithm if necessary.
To multiply every cell as you go through the grid you can loop through multiplying the values and adding it to a variable... First we'll make sure there is a value and if so lets try and cast that value as a double. If so multiply the old values with the new one and so on...
Dim dblTotal As Double = 0
Dim dblValue As Double = 0
For i As Integer = 0 To MetroGrid1.Rows.Count - 1
If MetroGrid1.Rows(i).Cells("Quota").Value IsNot DBNull.Value Then
If Double.TryParse(MetroGrid1.Rows(i).Cells("Quota").Value.ToString, dblValue) Then
dblTotal *= dblValue
End If
End If
Next

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
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.