Question

I'm calculating product prices after discounts. An example would be product A would be 100 dollars with a 11.5% discount. When I store the 11.5% discount in a decimal as something like

myDecimal = 0.885M

the variable gets rounded to 2 places to become 0.89. Am I using the wrong datatype? I'm not sure what else to use because I was taught not to use floating point values because of the math errors.

What would be a solution?

Was it helpful?

Solution

You are just looking at the string representation of your decimal, which appears to be giving you 2 decimals, try using a different string format specification something like this.

static void Main(string[] args)
{
    decimal myDecimal = 0.885M;
    Console.WriteLine(myDecimal.ToString("N"));
    Console.WriteLine(myDecimal.ToString("N3"));
    Console.ReadLine();
}

The default Decimal.ToString() implementation according to MSDN states:

The ToString method formats a Decimal value in the default ("G", or general) format of the current culture.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top