0

I need to set “0” at the end of the decimal place dynamically if less integer number found after decimal place.

Suppose we have value: “535.8” Now I need to set it as “535.800” I have following code:

string cost = "535.8";
string decplace = "3";

decimal price = decimal.Round(Convert.ToDecimal(cost), Convert.ToInt32(decplace));
Console.WriteLine(price);
Console.ReadLine();

Unable to get 535.800.

How can I achieve this?

Puppy
  • 144,682
  • 38
  • 256
  • 465

3 Answers3

1

You can convert price to string and show upto 3 decimal places with 0's at end.

            string cost = "535.8";
            string decplace = "3";

            decimal price = decimal.Round(Convert.ToDecimal(cost), Convert.ToInt32(decplace));
            //string.Format("{0:N2}", price);
            Console.WriteLine(string.Format("{0:N3}", price));
PawanS
  • 7,033
  • 14
  • 43
  • 71
0
price.ToString("N3")

Standard Numeric Format Strings: The Numeric ("N") Format Specifier

So if the number of decimal should be dynamic:

int numDecimalPlaces = 3;
Console.WriteLine(price.ToString("N" + numDecimalPlaces));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

You can use string.Format() to make it possible:

Console.WriteLine(string.Format("{0:N3}", d));

So in your code:

string cost = "535.8";
string decplace = "3";

decimal price = decimal.Round(Convert.ToDecimal(cost), Convert.ToInt32(decplace));
Console.WriteLine(string.Format("{0:N" + decplace + "}", price);
Console.ReadLine();
Nickon
  • 9,652
  • 12
  • 64
  • 119