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! :)
Related
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
I'm using this query in vb.net
Raw_data = Alltext_line.Substring(Alltext_line.IndexOf("R|1"))
and I want to increase R|1 to R|2, R|3 and so on using for loop.
I tried it many ways but getting error
string to double is invalid
any help will be appreciated
You must first extract the number from the string. If the text part ("R") is always separated from the number part by a "|", you can easily separated the two with Split:
Dim Alltext_line = "R|1"
Dim parts = Alltext_line.Split("|"c)
parts is a string array. If this results in two parts, the string has the expected shape and we can try to convert the second part to a number, increase it and then re-create the string using the increased number
Dim n As Integer
If parts.Length = 2 AndAlso Integer.TryParse(parts(1), n) Then
Alltext_line = parts(0) & "|" & (n + 1)
End If
Note that the c in "|"c denotes a Char constant in VB.
An alternate solution that takes advantage of the String type defined as an Array of Chars.
I'm using string.Concat() to patch together the resulting IEnumerable(Of Char) and CInt() to convert the string to an Integer and sum 1 to its value.
Raw_data = "R|151"
Dim Result As String = Raw_data.Substring(0, 2) & (CInt(String.Concat(Raw_data.Skip(2))) + 1).ToString
This, of course, supposes that the source string is directly convertible to an Integer type.
If a value check is instead required, you can use Integer.TryParse() to perform the validation:
Dim ValuePart As String = Raw_data.Substring(2)
Dim Value As Integer = 0
If Integer.TryParse(ValuePart, Value) Then
Raw_data = Raw_data.Substring(0, 2) & (Value + 1).ToString
End If
If the left part can be variable (in size or content), the answer provided by Olivier Jacot-Descombes is covering this scenario already.
Sub IncrVal()
Dim s = "R|1"
For x% = 1 To 10
s = Regex.Replace(s, "[0-9]+", Function(m) Integer.Parse(m.Value) + 1)
Next
End Sub
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
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 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)