Reputation: 47607
How to parse string to decimal so it would work for both formats - w/ commas and periods?
[Fact]
public void foo(){
var a="1,1";
var b="1.1";
Assert.Equal(Parse(a),Parse(b));
}
private decimal Parse(string s){
return decimal.Parse(s,NumberStyles.Any,
CultureInfo.InvariantCulture);
}
output:
Test 'Unit.Sandbox.foo' failed: Assert.Equal() Failure
Expected: 11
Actual: 1,1
Upvotes: 7
Views: 24419
Reputation: 97
If you have an English-language operating system, this method converts a decimal number with a comma to a dot. If you have Russian, the method converts a decimal number with a dot to a comma.
Console.Write("Input number: ");
string? input = Console.ReadLine();
decimal number = ConvertNumberToCurrentLocale(input);
Console.WriteLine("Result: " + number);
decimal ConvertNumberToCurrentLocale(string? input)
{
string separator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
switch (separator)
{
case ".":
input = input?.Replace(",", ".");
break;
case ",":
input = input?.Replace(".", ",");
break;
}
decimal.TryParse(input, out var number);
return number;
}
Upvotes: 0
Reputation: 6851
How about this?
private static decimal Parse(string s)
{
s = s.Replace(",", ".");
return decimal.Parse(s);
}
Upvotes: 6
Reputation: 292465
You could try that:
private decimal Parse(string s){
s = s.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
return decimal.Parse(s,NumberStyles.Any,
CultureInfo.InvariantCulture);
}
Upvotes: 10
Reputation: 2354
You should get the desired result by modifying the Currency decimal separator to a comma before a parse on a comma decimal string. There are some food resources here:
You could alternatively implement your own Iformatprovider as discussed here:
http://msdn.microsoft.com/en-us/library/t7xswkc6.aspx http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx
Oh, or you could do a dirty hack and simply run a string replace on "," with "." ;)
Upvotes: 1