how to fix this error. . when user input whole number and multipy it there's no problem in this part of my code
but when user input a fractional number(negative or positive) like "1/2,-2/3 ETC" there is an error
the error is pointing in: new1 = CDbl(txta1.Text) * CDbl(txtb2.Text) * CDbl(txtc3.Text)
Error Message: Conversion from string "1/2" to type 'Double' is not valid.
view plaincopy to clipboardprint?
Dim new1, new2, new3, new4, new5, new6, add1, add2, minus1 As Double
new1 = CDbl(txta1.Text) * CDbl(txtb2.Text) * CDbl(txtc3.Text)
new2 = CDbl(txta2.Text) * CDbl(txtb3.Text) * CDbl(txtc1.Text)
new3 = CDbl(txta3.Text) * CDbl(txtb1.Text) * CDbl(txtc2.Text)
new4 = CDbl(txtc1.Text) * CDbl(txtb2.Text) * CDbl(txta3.Text)
new5 = CDbl(txtc2.Text) * CDbl(txtb3.Text) * CDbl(txta1.Text)
new6 = CDbl(txtc3.Text) * CDbl(txtb1.Text) * CDbl(txta2.Text)
Please activate Option strict ON, which will help you to prevent rookie mistakes like trying to use a textfield like txta1.text as a number:
http://support.microsoft.com/kb/311329
You have to try to parse a value from text to a number like so:
Dim number1 As Double
If Double.TryParse(txta1.Text, number1) Then
// do something
Else
Console.WriteLine("{0} is outside the range of a Double.", _
value)
// report error
End If
Otherwise it is very hard to debug your code.
As to fractions: I would be very hard to parse a fraction reliably by hand. I would somethink prebuild, like a mathematic expression library. Take a look: https://ncalc.codeplex.com/
"1/2" is a string and must be parsed and converted into a numeric by your code.
Here is an example.
For use with simple fractions (as shown in your example), decimals and negative numbers.
Note: You should add error checking. For brevity, I did not include any error checking.
Dim strInput As String = "-1/2"
Dim dblValue As Double = Nothing
If strInput.Contains("/") Then ' A fraction
Dim strArray() As String = strInput.Split(CChar("/"))
dblValue = CDbl(strArray(0)) / CDbl(strArray(1))
Else
dblValue = CDbl(strInput)
End If
Console.WriteLine(dblValue)
Related
I've done some research and the general advice is changing the datatype of the variable holding the expression to Long or Ulong but in either case, I'm still getting the same error. I also tried enclosing the expression with CInt() (or CLong()) to force it to cut out it's decimal portion to reduce the length of the output of the expression but neither is working. It's all pretty confusing. Any help will be deeply appreciated. The code block triggering the error is as follows;
Vsf(i) = CInt((((0.91544 - 0.00166 * Angle(i) - 0.000002 * W - 0.054248 *
Superelevation(i) - Sidefrictionfactor) / 0.013939) * Radius(i)) ^ 0.5)
Vro(i) = CInt((((1.04136 - 0.004528 * Angle(i) - 0.000004 * W - 0.338711 * Superelevation(i) - rolloverthreshold) / 0.014578) * Radius(i)) ^ 0.5)
Vmin(i) = CInt(Math.Min(Vsf(i), Vro(i)))
I declared VSf(), Vro() and Vmin() all as integer arrays. I even enclosed the computation expression in a CInt() in hopes that it would convert the result of Vro (which was triggering the arithmetic overflow error) to an integer and hence not have to deal with decimals which would lead to more digits. Yet when I hover over Vro(i), I see a 4 digit integer with decimals. Not sure why that's happening.
I broke the formula down to try and see where the problem was occurring. Everything buzzed along until the very end. If the value to be raised to .5 is a negative number, the square root does not produce a number. I would perform the steps of the formula without the ^.5 and then check for a negative number.
Private Sub OPCode()
Dim Angle = 90.2
Dim Radius = 100.2
Dim Superelevation = 37.8
Dim Sidefrictionfactor = 0.003
Dim W = 0.00325
Dim Vsf As Double
Dim AngleMultiplication = 0.00166 * Angle
Dim WMultiplication = 0.000002 * W
Dim SuperelavationMultiplication = 0.054248 * Superelevation
Dim SubtractResult = 0.91544 - AngleMultiplication - WMultiplication - SuperelavationMultiplication - Sidefrictionfactor
Dim DivisionResult = SubtractResult / 0.013939
Dim MultiplyByRadius = DivisionResult * Radius
Debug.Print(MultiplyByRadius.ToString) 'With my made up values I get a negative number
Vsf = MultiplyByRadius ^ 0.5 'You cannot get the square root of a negative number
Debug.Print(Vsf.ToString) 'NaN
Dim intVsf = CInt(Vsf) 'The Arithematic overflow error occurs here
End Sub
I am currently using this formula to round a number that I am getting from an API
Dim editedRatio As Decimal = Decimal.Round(Convert.ToDecimal(growth), 0)
returnRatio = editedRatio.ToString("0,0,,", CultureInfo.CurrentCulture)
returnRatio = "$" & returnRatio.Substring(0, returnRatio.Length - 2) & "B"
The result is $44,9B
I am attempting to get back $44.9B
I've tried adjusting the to editedRatio.ToString("0.0,,") but it ends up breaking the rounding formula for example : 44954308000
Is there a way to convert the comma to a decimal point?
You can try something like this:
Since it looks like you want to return a formatted number which is the result of the conversion of the original input string to a decimal representation, where the initial value is divided by (1000 ^ [thousands separators]).
It's not actually clear if this is the expected value, but the division:
editedRatio = Decimal.Divide(editedRatio, CDec(1000 ^ (growth.Length \ 3)))
can be modified in simply:
editedRatio = Decimal.Divide(editedRatio, (1000 ^ 3)
if this is instead the expected output. Or any other specific value defined by the conversion rule.
Note1: the decimal is converted to string using {N2} since {N1} causes rounding
Note2: you could also use new CultureInfo("en-Us") and {C2} format instead of CultureInfo.InvariantCulture and {N2} to insert the $ symbol. But I'm not sure $ is actually meant to represent currency here.
With growth = "44954308000":
Dim editedRatio As Decimal = 0.0D
Dim returnRatio As StringBuilder = New StringBuilder()
If Decimal.TryParse(growth, editedRatio) Then
editedRatio = Decimal.Divide(editedRatio, CDec(1000 ^ (growth.Length \ 3)))
returnRatio.AppendFormat(CultureInfo.InvariantCulture, "${0:N2}", editedRatio)
returnRatio.Remove(returnRatio.Length - 1, 1).Append("B")
End If
Console.WriteLine(returnRatio)
Prints: $44.9B
Private Sub my_method01()
Dim returnratio As String = "44954308000"
Dim editedRatio As Decimal = Decimal.Round(Convert.ToDecimal(returnratio), 0)
returnratio = editedRatio.ToString("0,0,,", System.Globalization.CultureInfo.CurrentCulture)
returnratio = "$" & returnratio.Substring(0, returnratio.Length - 2) & "B"
'Displays: "$44.9B"
End Sub
I hope it likes to you. Thank you very much. Happy codding! :)
just have a problem with visual basic. I was trying to make a simple conversion program, but the program keeps giving me the wrong answer. I've also coded this out in Java, where it gave me the answer I was expecting. I don't know what's going on here. Here is a sample of the code. The numbers I have been entering are 10 for alienYears to convert, 440 for alienYearLength and 25.5 for alienDayLength. It should come out to about 12. something but I keep getting 218.something.
Thank you
Dim alienYears As Decimal = CDec(txtYearsToConvert.Text)
Dim alienYearLength As Decimal = CDec(txtDaysOnAlienPlanet.Text)
Dim alienDayLength As Decimal = CDec(txtDaysOnAlienPlanet.Text)
Dim alienHoursYears As Decimal = ((alienYears * alienYearLength) * alienDayLength)
Dim earthHourYears As Decimal = (8851.25)
Dim earthConversion As Decimal = (alienHoursYears / earthHourYears)
txtAgeOnEarth.Text = CStr(earthConversion)
Looks like a typo here (vvvv), do you mean txtYears(something)? There's no way this could be meaningful using the input from the same textbox.
Dim alienYears As Decimal = CDec(txtYearsToConvert.Text)
' VVVV
Dim alienYearLength As Decimal = CDec(txtDaysOnAlienPlanet.Text)
Dim alienDayLength As Decimal = CDec(txtDaysOnAlienPlanet.Text)
Dim alienHoursYears As Decimal = ((alienYears * alienYearLength) * alienDayLength)
Dim earthHourYears As Decimal = (8851.25)
Dim earthConversion As Decimal = (alienHoursYears / earthHourYears)
txtAgeOnEarth.Text = CStr(earthConversion)
I am getting a warning:
Severity Code Description Project File Line Suppression State
Warning BC42322 Runtime errors might occur when converting 'String' to 'IFormatProvider'.
I have 2 .ToString("N0") in my code in the same Sub. Can I not have 2 in the same sub? They go to different labels but, I am new to VB as well so please do not judge. Thanks!
If Integer.TryParse(input, infantry) Then
Dim hpai = Integer.Parse(frmMainGame.lblHPAI.Text, Globalization.NumberStyles.AllowThousands, Globalization.CultureInfo.InvariantCulture)
frmMainGame.lblHPAI.Text = (hpai - infantry * 2).ToString("N0")
frmMainGame.lblInfantryNumberPlayer.Text -= input.ToString("N0") '<---- One that gets the warning
Else
' handle not an int inputted case
End If
Let's look at this line:
frmMainGame.lblInfantryNumberPlayer.Text -= input.ToString("N0")
You're applying the -= operator to STRINGS. This operator has no meaning for strings. Are you trying to apply some kind of reverse-concatenation? Removing any occurrence of input from within the label text? That code just doesn't make sense at all.
If you're actually trying to do a numeric operation, you need to actually work with numbers... convert the label string to an integer, not the integer to a string.
If Integer.TryParse(input, infantry) Then
Dim hpai = Integer.Parse(frmMainGame.lblHPAI.Text, Globalization.NumberStyles.AllowThousands, Globalization.CultureInfo.InvariantCulture)
frmMainGame.lblHPAI.Text = (hpai - infantry * 2).ToString("N0")
Dim numPlayer = Integer.Parse(frmMainGame.lblInfantryNumberPlayer.Text)
frmMainGame.lblInfantryNumberPlayer.Text = (numplayer - input).ToString("N0") '<---- One that gets the warning
Else
' handle not an int inputted case
End If
I was quickly copying code from something else. Upon testing and debugging, I kept getting really strange results. After comparing the code again, I realized that I had added an extra = inside of my equation:
Dim lowerLeft As Integer = x = +y * terrainWidth
as opposed to this:
Dim lowerLeft As Integer = x + y * terrainWidth
What was this actually doing?
If you had Option Strict On (and you should), this wouldn’t compile.
A = inside an expression is a comparison operator. Its result is a Boolean. In your case, this means the expression is equivalent to:
Dim lowerLeft As Integer
If x = +y * terrainWidth Then
lowerLeft = True ' Converted to 1
Else
lowerLeft = False ' Converted to 0
End If
Option Strict On rightly forbids this implicit conversion.