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
To parse a string with commas to a number: Use the replace() method to remove all the commas from the string. The replace method will return a new string containing no commas. Convert the string to a number.
Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.
To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.
Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.
You could try that:
private decimal Parse(string s){
s = s.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
return decimal.Parse(s,NumberStyles.Any,
CultureInfo.InvariantCulture);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With