user987316
user987316

Reputation: 942

String formatting as per current locale

In my C# application I am using string as

string sTemp = "10.12;12.13;15.345";

Now I would like to know is there any way I could format this string and its contents(specially when they are numbers) as per current locale. Ultimately I want my sTemp should be - "10,12;12,13;15,345" in french locale.

Is it possible?

Upvotes: 0

Views: 703

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460228

Use String.Split(';') to split the string-doubles, double.Parse with CultureInfo.InvariantCulture to parse the input and double.ToString with CultureInfo.CurrentCulture (or "fr-FR") to parse the output:

string sTemp = "10.12;12.13;15.345";

var doubles = sTemp.Split(';')
    .Select(s => double.Parse(s, CultureInfo.InvariantCulture));

var locale = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR");
// or var locale = System.Globalization.CultureInfo.CurrentCulture;

var localeDoubleStrings = doubles.Select(d => d.ToString(locale));
foreach(string frDoubleStr in localeDoubleStrings)
    Console.WriteLine(frDoubleStr);

Demo

Upvotes: 1

V4Vendetta
V4Vendetta

Reputation: 38220

I guess you are using the string with the contents as declared in that case you need to have it formatted

Example

// this would be as per french culture
Console.WriteLine(string.Format(new CultureInfo("Fr-fr"), "{0};{1};{2};", 10.2, 15.6, 25.3));
// this would be invariant
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0};{1};{2};", 10.2, 15.6, 25.3));

so you would need to just say CultureInfo.CurrentCulture and that should work for you.

But if you are using it with the contents then you have to update the question with how you are building the string content

Upvotes: 0

Jobo
Jobo

Reputation: 1084

string sTemp = "10.12;12.13;15.345";
string[] splitted = sTemp.Split(';');
IEnumerable<float> floats = splitted.Select(s => float.Parse(s, System.Globalization.CultureInfo.InvariantCulture));

string localized = floats.Select(f => f.ToString()).Aggregate((current, next) => current + ";" + next);

Upvotes: 2

Related Questions