I have got a model which contains a property of data type decimal. I want to make sure the getter method returns a deterministic value in every case.
The data type model stores the number of non-significant decimal places, but does not seem to expose a method or property to control it.
The following program illustrates the findings:
class Program
{
static void Main(string[] args)
{
decimal d1 = decimal.Parse("1200.00");
Console.WriteLine(d1); // Prints 1200.00
decimal d2 = decimal.Parse("1200");
Console.WriteLine(d2); // Prints 1200
decimal d3 = correctDecimalPlaces(d2);
Console.WriteLine(d3); // Prints 1200.00
}
static decimal correctDecimalPlaces(decimal d)
{
return decimal.Parse(d.ToString("0.00"));
}
}
How can I control the number of decimal places used in decimal data type?
To change the number of decimal values, I convert the decimal to a string and back to a decimal. Do you know a cleaner way to do it?