Difficulty with a Visual Basic calculation - vb.net

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)

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

Rounding number from API - VB.NET - CultureInfo

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! :)

How to use substring() function to get middle string with relative index?

I want to extract characters from a string. However, the string doesn't have the same length every time.
Basically I get data from a database and I want extract the value I need in it. But I'm stuck on step where I have to extract the right value.
So first I get data like that :
infoDataset2 = accessRequet_odbc("select st_astext(st_snaptogrid(geom, 0.01)) from netgeo_point_tech", myConnection)
The result is something like : POINT(921021.98 6671778.45). What I need are the 2 figures, but their length is not fixed. I just want to remove POINT( and ).
Then I work on each line of the DataSet I get to cast each lines into a string with only the value needed.
For i = 0 To infoDataset2.Tables(0).Rows.Count - 1
geomPt = infoDataset2.Tables(0).Rows(i).ItemArray(0).Substring(geomPt = infoDataset2.Tables(0).Rows(i).ItemArray(0).Substring(1 + infoDataset2.Tables(0).Rows(i).ItemArray(0).LastIndexOf("(")))
Console.WriteLine(geomPt)
Next
This was my last try, where I was able to remove POINT( but I'm struggling with the length to cut ).
I want to learn from this, so, if possible, explain to me what I'm doing wrong here, or if my approach is lacking insight.
It will be horrible to debug that one long line. It makes no difference to the computer if you split it up into easy-readable parts. Here's some code to get the x- and y-coordinates from a string formatted as shown in the question:
Dim s = "POINT(921021.98 6671778.45)"
Dim b1 = s.IndexOf("("c) + 1
Dim b2 = s.IndexOf(")"c, b1) - 1
Dim parts = s.Substring(b1, b2 - b1 + 1).Split({" "c})
Dim x As Decimal = Decimal.Parse(parts(0))
Dim y As Decimal = Decimal.Parse(parts(1))
Another way of parsing the string is to use a regular expression, which can be more flexible. In this example, I used named capture groups to make it easy to see which parts are for the x and y:
Dim s = "POINT(921021.98 6671778.45)"
Dim x As Decimal
Dim y As Decimal
Dim re = New Regex("\((?<x>[0-9-.]+) (?<y>[0-9-.]+)\)")
Dim m = re.Match(s)
If m.Success Then
x = Decimal.Parse(m.Groups("x").Value)
y = Decimal.Parse(m.Groups("y").Value)
Else
' Could not parse point. Do something about it if required.
End If
Andrew Morton has given a nice answer, i upvoted that one, if you need an even easier way and that was still complicated use this
Dim s = "POINT(921021.98 6671778.45)"
Dim part1 As String = s.Remove(0, 6)
Dim part2 As String = part1.Substring(0, part1.Length - 1)
Dim split() As String = part2.Split(" ")
Dim x = split(0)
Dim y = split(1)
Here is an even probably easier to understand solution:
Dim s as String = "POINT(921021.98 6671778.45)"
Dim coordinate() as String = s.Replace("POINT(", "").Replace(")", "").Split(" ")
Enjoy!

Losing decimal while dividing in visual basic

I'm having to create a random math generator in visual basic, when a user selects divide it should show the number to the second decimal. Anything I have tried so far keeps rounding off.
option strict on is required
this is the code I have so far
Private Sub DivisionProblem()
' Divide two numbers and display the answer
Dim numSmallestNum As Integer = CreateANumber()
Dim numLargestNum As Integer = CreateANumber()
Dim strToWork As String
If (numLargestNum > numSmallestNum) Then
strToWork = (Convert.ToString(numLargestNum) & " / " & Convert.ToString(numSmallestNum))
lblToWork.Text = strToWork
_decAnswer = CInt((Decimal.Round(CDec(numLargestNum / numSmallestNum), 2)))
Else
strToWork = (numSmallestNum & " / " & numLargestNum)
lblToWork.Text = strToWork
_decAnswer = CInt((Decimal.Round(CDec(numSmallestNum / numLargestNum), 2)))
End If
End Sub
if anyone has any suggestions I would greatly appreciate it. thank you!
CInt forces the value to be of Integer not Double.
Dim numSmallestNum As Integer = CreateANumber()
Dim numLargestNum As Integer = CreateANumber()
Declare these two As Decimal and there's no need to convert anything.
You'll want to Dim _decAnswer as Decimal and use CDec instead of CInt.
For additional context on the Decimal type, check out this article
You might also want to consider using Double and CDbl instead of Decimal and CDec, depending on your use case.
Well as far as I know an Integer does not save decimals. Use Dim ... As Decimal. Just make life easier

Determine digits decimal point

I am working on this simple VB.net application that allows users to enter a decimal number (ex - 1.23) and the program lists what the digits are to the left and right of the decimal and as well as how many actual digits are to the left and right of the decimal. Here is what my code looks like so far.
Dim imput As String
imput = txtEnterNumber.Text
Dim D As Integer
D = txtEnterNumber.Text.IndexOf(".")
txtNumLeft.Text = imput.Remove(D)
txtNumRight.Text = imput.Remove(0, D)
txtDigitLeft.Text = CStr(imput.Substring(0, D).Length)
txtDigitRight.Text = CStr(imput.Substring(D).Length)
When I run my program it includes the decimal point for what the digits are to right of the decimal and as well as how many digits are right of the decimal. Why is this?
Thanks!
Try this
Dim imput As String
imput = txtEnterNumber.Text
Dim D As Integer
D = txtEnterNumber.Text.IndexOf(".")
txtNumLeft.Text = imput.Remove(D)
txtNumRight.Text = imput.Remove(0, D + 1)
txtDigitLeft.Text = CStr(imput.Substring(0, D).Length)
txtDigitRight.Text = CStr(imput.Substring(D + 1).Length)
Your substring is taking a substring from the decimal point, giving a +1 position in SUBSTRING will solve it. Also, you can simplify your code using SPLIT function:
Dim num() as string = txtEnterNumber.Text.Split(".")
txtNumLeft.Text = num(0)
txtDigitLeft.Text = num(0).Length
If(num.Length > 1)Then
txtNumRight.Text = num(1)
txtDigitRight.Text = num(1).Length
Else
txtNumRight.Text = ""
txtDigitRight.Text = 0
End If