Decimal number in CSV file - vb.net

My application generates CSV file from some objects. These CSV files are used in many countries so I must use correct separator.
To seperate values (cells) in a file I use separator:
Dim separator As String = My.Computer.Info.InstalledUICulture.TextInfo.ListSeparator
This should be OK. But one column contains decimal numbers so I want to be sure that I use correct decimal separator (must be different than list separator).
I am converting decimal value to a string like this:
Dim intValue as Integer = 123456
Dim strValue as String = (intValue / 100).ToString()
In my country a list separator is a semicolon and decimal separator is a comma. In this combination it is OK. But I found out that in some country where the list separator is a comma, decimal separator is comma as well. And this is a problem. How I have to convert a decimal number to string if I want to use correct local decimal separator? Thanks!

How I have to convert a decimal number to string if I want to use
correct local decimal separator?
By default the current culture's separator is used anyway. But you can use the overload of Decimal.ToString that takes a CultureInfo:
Dim localizedNumber = (intValue / 100).ToString( CultureInfo.CurrentCulture )
If you want to use a different culture:
Dim usCulture = new System.Globalization.CultureInfo("en-US")
localizedNumber = (intValue / 100).ToString( usCulture )
If you want to know the decimal separator of a given culture:
Dim separator As String = usCulture.NumberFormat.NumberDecimalSeparator
Edit So your customers don't want to use tab as separator since they have to specify the delimiter manually. You could either generate a real excel-file, for example by using EPPlus which doesn't even need an excel-license or you need to provide another solution.
I have checked it, there are 13 cultures where the decimal-separator is the same as the list-separator (used by excel):
Dim conflictCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures).
Where(Function(c) c.NumberFormat.NumberDecimalSeparator = c.TextInfo.ListSeparator)
So you have to check it manually and then provide a different list-separator. If decimal/list-separator is comma you can use semicolon as list-separator and vice-versa:
Dim argentinaCulture = New CultureInfo("es-AR") ' uses same separator for both
Dim decimalSeparator = argentinaCulture.NumberFormat.NumberDecimalSeparator ' comma
Dim listSeparator = argentinaCulture.TextInfo.ListSeparator 'comma
If decimalSeparator = listSeparator Then
listSeparator = If(listSeparator = ",", ";", ",")
End If

Related

converting integer to decimal values while adding both

I am working on a vb.net application.
My code is the following:
txtTotalPrevious.Text = Val(txtTotalPrevious.Text) + Val(txtoldtotal.text)
my values are:
txtTotalPrevious.Text=187.0000
txtoldtotal=3
I get the result
result =190
but my expected result is:
result=190.0000
What is the issue in my logic?
You can use String.Format if you want to output string be like you want:
Dim str1 As String = "187.0000"
Dim str2 As String = "3"
Dim resultString As String = String.Format("{0:0.0000}", Val(str1) + Val(str2))
' And the result will be 190.0000
And if you want the double result:
Dim resultDouble as Double= Val(str1) + Val(str2)
' And the result will be Double 190
EDIT
Based on varocarbas comments you should consider some notes:
Avoid using Val method
The Val function stops reading the string at the first character it
cannot recognize as part of a number. Symbols and characters that are
often considered parts of numeric values, such as dollar signs and
commas, are not recognized. However, the function recognizes the radix
prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and
linefeed characters are stripped from the argument.
The following call
returns the value 1615198.
Val(" 1615 198th Street N.E.")
The Val function recognizes only the period (.) as a valid decimal
separator. When different decimal separators are used, as in
international applications, use CDbl or CInt instead to convert a
string to a number. To convert the string representation of a number
in a particular culture to a numeric value, use the numeric type's
Parse(String, IFormatProvider) method. For example, use Double.Parse
when converting a string to a Double.
As a VB.Net Programmer use & instead of + for string concatenation
When you use the + operator, you might not be able to determine
whether addition or string concatenation will occur. Use the &
operator for concatenation to eliminate ambiguity and to provide
self-documenting code.

using IndexOf in Mid function

Perhaps this is a simple solution for most, but I can't get this to work like it should according to syntax.
I have this line of text "Part Number123456Price$50.00"
I want to pull the part number out of it, so I use this function...
str = Mid(str, str.IndexOf("Part Number") + 12, str.IndexOf("Price"))
My results are str = "123456Price$50.0" every time. I know the part number can vary in length so I need a solid solution of pulling this out.
It can be confusing to mix the legacy VB string methods (such as Mid) with the .Net string methods (like IndexOf). The VB methods use 1 as the index of the first character while the .Net methods use 0.
The following code will extract the part number from a string
Dim str As String = "Part Number123456Price$50.00"
Dim iPart As Integer = str.IndexOf("Part Number") + 11
Dim iPrice As Integer = str.IndexOf("Price")
str = str.Substring(iPart, iPrice - iPart).Trim
The Mid() function of Visual Basic is documented as having three arguments: (1) a string, (2) the beginning location in the string, and (3) the number of characters to copy.
So if your string is "Part Number123456Price$50.00" and you want to pull the part number as a series of digits, the "123456" part of the string, using the Mid() function then you need to find the beginning of the part number digit string and to then know the number of digits.
If your string is in the variable str then you can find the offset by something like str.IndexOf("Number") + len("Number") which will provide the offset to after the string "Number".
Next you need to find the number of digits so you would do something like str.IndexOf("Price") to find where the text "Price" begins and then subtract from that offset the offset of where the digits begin.
The result of all of this is you need a bit of code something like the following. I have not tested this source as I am not a VB programmer so it may need a tweak and you might want to put some checks on data validity as well.
Dim TextNumber as String = "Number"
Dim TextPrice as String = "Price"
iOffset = str.IndexOf(TextNumber) + len(TextNumber)
str = Mid(str, iOffset, str.IndexOf(TextPrice) - iOffset)
Alternatively, if Price is always the format $00.00, this will also work.
Dim str as String = "Part Number123456Price$50.00"
str = str.Remove(str.IndexOf("Price"))

How do I split a string every 7th charecter in VB

I am having difficulties trying to figure out the syntax. I have a line of binary in a variable and i want to know how to to split that string every 7th character so i can put it in an ascii table to find its equivalent.
Based on your scenario, you can also do a substring to satisfy your requirement.
Dim theString As String = "w3rs0fd90as90f9sda0faf"
Dim FirstSevenCharacters as String= theString.Substring(0, 7)
Dim CharactersAfterTheFirstSeven as String= theString.Substring(7, theString.Length - 7)

Spliting a string based on multiple characters

I am trying to split a string with multiple characters. The string might sometimes contain a - or a /. What I have achieved is the hyphen but I am not able to search for the slash. Any thoughts on how to split the string based on both characters at once ? Once I split after - I add the value after the - to the result list as a separate index and I would like to accomplish the same for '/'.
So For example the Split string has Jet-blue, the below code will add Jet in the result list with index(0) and blue with index(1). In addition to splitting with '-' I would also like to split with '/'. Any suggestions ?
Code:
Dim result As New List(Of String)()
For Each str_get As String In Split
Dim splitStr = str_get.Split("-")
For Each str_split As String In splitStr
result.Add(str_split) ' Enter into result list
' result.TrimExcess()
Next
result.Remove("")
Next
You can either use this or this overload of the Split method.
The first one takes an array of Char:
"Hello World".Split({"e"c, "o"c}) ' Notice the c!
The second one takes an array of String and StringSplitOptions:
"Hello World".Split({"el", "o"}, StringSplitOptions.None)

splitting a string to access integer within it

i have a string "<PinX F='53mm'></PinX>", I want to access the 53 within the string and do some addition to it and then add the answer back into that string. I've been thinking about this and wasn't sure whether this can be done with regular expression or not? Can anybody help me out.
thanks
Yes, you can use a regular expression. This will get the digits, parse them to a number, add one to it, and put it back in the string (that is, the result is actually a new string as strings are immutable).
string s = Regex.Replace(
input,
#"(\d+)",
m => (Int32.Parse(m.Groups[1].Value) + 1).ToString()
);
Take a look at the HTML Agility Pack.
A regular expression looks like a good fit for this particular problem:
\d+
Will match one or more digits.
Int32.Parse(Regex.Match("<PinX F='53mm'></PinX>", #"\d+").Value)
Will return 53.
In this single case yes. "'(.*?)' then access the first group, but if this is part of a larger xml regular expressions should not be used. You should utilize the xml parser build into .net find the attribute with xsd and get the value.
Alternatively, here's a small routine...
' Set testing string
Dim s As String = "<PinX F='53mm'></PinX>"
' find first occurence of CHAR ( ' )
Dim a As Integer = s.IndexOf("'")
' find last occurence of CHAR ( ' )
Dim b As Integer = s.LastIndexOf("'")
' get substring "53mm" from string
Dim substring As String = s.Substring(a, b - a)
' get integer values from substring
Dim length As Integer = substring.Length
Dim c As Char = Nothing
Dim result As String = Nothing
For i = 1 To length - 1
c = substring.Chars(i)
If IsNumeric(c) Then
result = result & c
End If
Next
Console.WriteLine(Int32.Parse(result))
Console.ReadLine()