Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string to decimal, commas and periods

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
like image 482
Arnis Lapsa Avatar asked May 02 '11 09:05

Arnis Lapsa


People also ask

How can I parse a string with a comma thousand separator to a number?

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.

How do you turn a string into a decimal?

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.

How do I change a comma separated string to a number?

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.

What does double parse do?

Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.


1 Answers

You could try that:

private decimal Parse(string s){
  s = s.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
  return decimal.Parse(s,NumberStyles.Any,
    CultureInfo.InvariantCulture);
}
like image 95
Thomas Levesque Avatar answered Oct 16 '22 19:10

Thomas Levesque