I am using the following to put decimal places when formatting an amount but I am not getting the correct amount when testing with eg 25000 I am expecting 25000.00
but I am getting 25000.
What I am doing wrong?How should I change it?
[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);
}
EDITED:
If you were to format a decimal value whatever the amount would always have 2 decimal even when is something like 25000 and you want 25000.00 or 1234.224543 returns 1234.22 how would you code it?
It looks to me like you’re passing in double values instead of decimals. Try this:
It’s possible that that won’t even build – I wouldn’t be surprised if
decimalvalues were disallowed in attributes as the CLR doesn’t know about them. If that does happen, you probably want to change the input to strings, parse them to decimals at the start of the test, and then compare them. You’ll need to check thatdecimal.Parsepreserves the trailing digits, of course… I think it does, but I can’t remember for sure offhand.Others have pointed out the “only round at the point of display, when you convert to a string” possibility – I can’t say whether or not that’s appropriate in your case. I know that there is a difference in representation between 25000m and 25000.00m. Whether you should be rounding to a given number of decimals will depend on your business requirements, of course.