Convert currency string to decimal?

后端 未结 6 928
北恋
北恋 2020-12-05 13:00

Objective

Sort a string that is displaying currency data like this $1,995.94 numerically in a set of data.

Code

I\'m cu

6条回答
  •  温柔的废话
    2020-12-05 13:12

    Here is a simpler solution:

        public static decimal ToDecimal(this string str)
        {
            return decimal.Parse(str, NumberStyles.Currency);
        }
    

    and the unit test:

        [Test]
        public void ToDecimal_Convert_String_To_Decimal()
        {
            Assert.AreEqual(1234M, "1234".ToDecimal());
            Assert.AreEqual(-1234.56M, "$(1,234.56)".ToDecimal());
            Assert.AreEqual(1234.56M, "$1,234.56".ToDecimal());
        }
    

提交回复
热议问题