用2个位置格式化十进制。问题

时间:2011-08-26 10:58:56

标签: c#

我在格式化数量时使用以下内容来放置小数位但是在测试时没有得到正确的数量,例如25000我期待25000.00 但是我得到了25000。

我做错了什么?我应该如何改变它?

                [TestCase(123.45453, 123.45, 2)]
                [TestCase(125.55453, 125.55, 2)]
                [TestCase(125.55653, 125.56, 2)]
                [TestCase(125.56554, 125.57, 2)]
                [TestCase(25000,25000.00,2)]

  public void MyRoundFunction_returns_amount_with_decimal_places(decimal amountToTest, decimal expected, int decimalPlaces)
                {
                    decimal actual = MyRoundFunction(amountToTest, MidpointRounding.ToEven, decimalPlaces);
                    Assert.AreEqual(expected, actual);
                }


         public static decimal MyRoundFunction(decimal value, MidpointRounding midpointRounding, int decimalPlaces)
                {
                    return Math.Round(value, decimalPlaces, midpointRounding);
                }

编辑:

如果你要格式化一个小数值,无论金额总是有2个小数,即使是25000这样你想要25000.00或1234.224543返回1234.22你会如何编码?

4 个答案:

答案 0 :(得分:6)

在我看来,你传递的是双值而不是小数。试试这个:

[TestCase(123.45453m, 123.45m, 2)]
[TestCase(125.55453m, 125.55m, 2)]
[TestCase(125.55653m, 125.56m, 2)]
[TestCase(125.56554m, 125.57m, 2)]
[TestCase(25000m, 25000.00m,2)]

有可能甚至不会构建 - 如果CLR不知道属性中的decimal值被禁止,我不会感到惊讶。如果发生,您可能希望将输入更改为字符串,在测试开始时将它们解析为小数,然后比较它们。你需要检查decimal.Parse是否保留了尾随的数字,当然......我认为确实如此,但我不记得了。

其他人已经指出“当你转换成字符串时”显示点的唯一一轮“可能性 - 我不能说你的情况是否合适。我知道 在25000m到25000.00m之间的表示差异。当然, 是否应该舍入到给定的小数位数取决于您的业务需求。

答案 1 :(得分:2)

您没有比较格式化的值。 decimal本身没有格式;当你将它表示为一个字符串时,格式就会出现在图片中。

答案 2 :(得分:0)

那是因为25000等于25000.00所以它正在修剪零。

我认为问题在于误解了小数位参数 - 这并不是说应该显示多少小数位,而是用于舍入和最大可能小数位数。

答案 3 :(得分:0)

@Fredrik是对的。

如果你想将它表示为字符串,你可以使用ToString(字符串格式)方法,如:

decimal number = 1200;
string formatted = number.ToString("#.###,00");

或其他格式化程序(请参阅http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx