Losing decimal while dividing in visual basic - vb.net

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

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

Difficulty with a Visual Basic calculation

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)

Calculating value of user-inputted equation

I'm working on building a simple limit calculator in Visual Studio 2013. Right now I have my program set up in a way so that the user first enters the equation for the limit, and then the limit value. (ex. equation of x+3, limit value of 3 - the answer should then be 6)
I'm designing it so that it takes the limit from both the left and right side of the user inputted number, and if the two answers then differ by quite a bit, the program will say the limit doesn't exist. (However this code isn't in place yet - I plan to work on it after I can solve this problem)
Anyway, right now I'm stuck on one part of my code. The user can input their own custom function, as I mentioned above. I then have the program automatically replace all "x" values with the limit value that the user input as well. However, when I have the answer display, it will give me an answer of 5.0001 + 3 instead of just 8.0001. Below is my code, do you know of any way I can fix this so that it will perform the calculations needed, and just spit out a single number rather than the equation with x substituted out?
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim Limit As Double = txtLimit.Text
Dim Equation As String = txtEquation.Text
Dim LeftTest As Double
Dim RightTest As Double
LeftTest = (Limit - 0.0001)
RightTest = (Limit + 0.0001)
Dim NewEquation = Replace(Equation, "x", RightTest)
Dim FinalAnswer
FinalAnswer = NewEquation
MsgBox("The limit for this equation is " & NewEquation)
End Sub
End Class
Any help would be appreciated with this.
You can download and use third party Parser.dll from the following link
http://simplemathparser.codeplex.com/
and code as shown below
Dim Limit As Double = txtLimit.Text
Dim Equation As String = txtEquation.Text
Dim LeftTest As Double
Dim RightTest As Double
LeftTest = (Limit - 0.0001)
RightTest = (Limit + 0.0001)
Dim parser As New MathParser.Parser("x")
Dim parsingResult = parser.Parse(Equation)
Dim result = parsingResult.Evaluate(RightTest)
MsgBox("The limit for this equation is " & result )

VB.net incremented number concatenate with texbox value

I'm learning vb.net. I'm trying to create an incremental number that starts at 00000 and concatenate that number with a value from a textbox (eg. JH00001), then insert it into the database.
Please can someone kindly help me with this as I'm totaly new to vb.net.
Thank you all for your assistance in advance. And I'm sorry for my bad English.
Dim number as Integer = 1
Dim text as String = textbox1.text &= number.toString().padLeft(5, "0"c)
Use D5 precision specifier to indicate that the number should be at least 5 digits including leading zeros:
Dim valueFromTextBox As String = "JH"
Dim value As String = ""
For i = 0 To 99
value = valueFromTextBox & i.ToString("D5")
'Insert value to database
Next
Check MSDN for more formatting methods
A for loop should be what you need:
Something like:
Dim text As String = textbox1.text
Dim DBtext As String
For value As Integer = 0 To 5
DBtext = text & value.ToString()
'Insert anything else you need to do. Such as insert into DB.
Next
Just replace the 5 with however many times you need it to run.
I personally prefer using String.Format ...
For i = 0 to 1e6-1
Dim FormattedString = String.Format("{0}{1:00000}", Textbox1.Text, i)
Next