Parse a string to decimal, comma and periods

How to parse a string to decimal so that it works 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 
+4
source share
3 answers

You can try the following:

 private decimal Parse(string s){ s = s.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator); return decimal.Parse(s,NumberStyles.Any, CultureInfo.InvariantCulture); } 
+6
source

How about this?

 private static decimal Parse(string s) { s = s.Replace(",", "."); return decimal.Parse(s); } 
+4
source

You should get the desired result by changing the decimal separator of the currency to a comma before analysis on a decimal string. There are some food resources here:

http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencydecimalseparator.aspx#Y888

You can also implement your own Iformatprovider, as described here:

http://msdn.microsoft.com/en-us/library/t7xswkc6.aspx http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx

Oh, or you can do a dirty hack and just start replacing the string with "," by ".";)

0
source

All Articles