skip to Main Content

I have prepared a C# fiddle for my question, however it does not really show the actual problem and correctly uses dots as decimal separator in the interpolated double values (UPDATED with Tim’s trick, thank you):

using System;
using System.Linq;

public class Program
{
    readonly static (double lng, double lat)[] Locations = 
    {
        (10.757938, 52.437444),
        (10.764379, 52.437314),
        (10.770562, 52.439067),
        (10.773268, 52.436633),
    };
    
    public static void Main()
    {
        string lngLats = Locations.Aggregate(string.Empty, (str, next) => str + $"{next.Item1:F6},{next.Item2:F6};");
        Console.WriteLine($"lngLats: {lngLats}n");
        
        double x = 12.3456;
        Console.WriteLine($"A double value: {x}n");
    }
}

However, when I run the same code on my Windows 10 Enterprise 22H2 computer, (set to English language, but German region) using Visual Studio 2022, then the decimal separator is a comma:

screenshot VS 2022

My question is: how to ensure that the decimal separator character is always a dot in the interpolated strings?

3

Answers


  1. String interpolation uses the current culture. So you need a workaround with double.ToString:

    double x = 12.3456;
    string result = x.ToString(System.Globalization.CultureInfo.InvariantCulture);
    Console.WriteLine($"A double value: {result}n");
    

    Your modified fiddle: https://dotnetfiddle.net/BTaONq

    So string interpolation doesn’t support a different culture. You could use string.Format:

    Console.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "A double value: {0}n", x));
    
    Login or Signup to reply.
  2. You can use the invariant culture like this

    string result1 = FormattableString.Invariant($"lngLats: {lngLats}n");
    string result2 = FormattableString.Invariant($"A double value: {x}n");
    

    With a using static System.FormattableString; you can simplify the calls and of course you can integrate this with the console output:

    string lngLats = Locations.Aggregate(
        string.Empty,
        (str, next) => str + Invariant($"{next.Item1:F6},{next.Item2:F6};")
    );
    Console.WriteLine($"lngLats: {lngLats}n");
    
    double x = 12.3456;
    Console.WriteLine(Invariant($"A double value: {x}n"));
    

    See also:

    Login or Signup to reply.
  3. I was thinking about this compromise, maybe?

    double x = 12.3456;
    Console.WriteLine($"A double value: {x.AsInvariant()}n");
    
    // with
    
    public static string AsInvariant(this double x) =>
       x.ToString(System.Globalization.CultureInfo.InvariantCulture);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search