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
Related
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
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
I have a label that shows too many decimal values.
For example,
textbox1 = 22
textbox2 = 7
label1 = textbox2/textbox1
I want label1 turn to 31.8 but it always turn to 31.8181811818181818881
I have already tried:
Dim label1 As String
label1 = (CInt(Me.textbox2.Text) / CInt(Me.textbox1.Text)) * 100
Format(label1, "0.00")
Form3.label1.Text = label1 + " %"
Acc. to your comment:
#KashishArora yes
I will do it in a very very simple way!
Explanation
We will first simply divide Textbox1 with Textbox2 and store the value in a label and then declare an integer a as label1.text (it isn't necessary to do it in variable, you can do directly). Then we will use the Math.Round control and specify the number of decimals we want (1 or 2).
And then finally, store the value of a back to Label1.
Code And Example
Label1.Text = Val(TextBox2.Text) / Val(TextBox1.Text)
Dim a As Double = Label1.Text
a = Math.Round(a, 2) '2 is number of decimal places
Label1.Text = a
'All the things you want to do with this.
I hope it works perfectly!
Use String.Format()...
Dim label1 As String
label1 = (CInt(Me.textbox2.Text) / CInt(Me.textbox1.Text)) * 100
label1 = String.Format("{0:0.0}", label1)
Form3.label1.Text = label1 & " %"
Just use the combination of substring and lastindexof
label1 = textbox2/textbox1
Dim labelText As String = label1.Text
labelText = labelText.Substring(0, labelText.LastIndexOf(".") +2) + "%"
You're all making this more complex than it is. Decimal.ToString has an overload where you can pass a standard or custom numeric format string.
In your case on should use the F{n} format specifier where {n} is the precision specifier indicating the desired number of decimal places.
label1.Text = (Decimal.Parse(textBox1.Text) / Decimal.Parse(textbox2.Text)).ToString("F2")
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.