Search code examples
c#visual-studioxamarindoubleseparator

C#: Convert string from array to double wih dot separator


I am developing an Xamarin Android app in Visual Studio.

I have a string array of GPS coordinates like this:

*string[] DeviceLocations = { "23.2342;32.4544", "7.4321;9.5431", "12.4223;-23.3434" };*

In order to be able to pass them to my Google Map like Markers, they have to be converted to double values - with the "." as separator.

I have tried several different ways to do this, including:

1)

Double lat = Convert.ToDouble(splitPos[0].ToString(), new CultureInfo("en-US"));

2)

NumberFormatInfo info = new NumberFormatInfo();
info.NumberGroupSeparator = ".";
info.NumberDecimalSeparator = ".";
Double lat = Double.Parse(splitPos[0].ToString(), info);

3)

Double lat = XmlConvert.ToDouble(splitPos[0].ToString());

4)

Double lat = double.Parse(splitPos[1].ToString(), CultureInfo.InvariantCulture);

But all of them returns the "lat" with a "," instead of a ".".

Anyone got any other ideas of what I can try??? I'm running out of ideas.


Solution

  • One correct way would be this:

    private static readonly CultureInfo USCULTURE = new CultureInfo("en-US");
    
    // Go over all items
    foreach (string latlon in DeviceLocations)
    {
        // Get the split result
        string[] coordinates = latlon.Split(';');
    
        // Lat is first item of split array, Lon is second item
        double lat = Convert.ToDouble(coordinates[0], USCULTURE);
        double lon = Convert.ToDouble(coordinates[0], USCULTURE);
    
        // Now do something with the double values
        ...
    }
    

    I don't know what you mean by all of them returns the "lat" with a "," instead of a ".", but a double is just a double. Only when you output it, there's a decimal separator. So maybe the system where you output the number has , as decimal separator?

    In that case you need to force the output to use US formatting:

    string outputtableLat = lat.ToString("G", USCULTURE);
    string outputtableLon = lon.ToString("G", USCULTURE);