Parse string to decimal, commas and periods

本小妞迷上赌 提交于 2019-12-07 02:07:22

问题


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

回答1:


You could try that:

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



回答2:


How about this?

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



回答3:


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:

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

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 "." ;)



来源:https://stackoverflow.com/questions/5855753/parse-string-to-decimal-commas-and-periods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!