DanielH
DanielH

Reputation: 953

Decimal number in CSV file

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!

Upvotes: 0

Views: 1754

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460068

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

Upvotes: 1

Related Questions