4

Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)

I'm trying to get my decimals to display with four decimal places. The DB rounds my number to 4 decimal places, but it returns the number with trailing 0s (due to the decimal precision of the field), so something like 9.45670000. Then, when I do this:

string.Format("{0:#,#.####}", decimalValue);

The output I get on the page is 9.4567, which is what I want.

However, if the number returned from DB is 9.45600000, the output after doing the format is 9.456

But what I need to display is 9.4560

How do I format my decimal, so that the number of decimal places is always four?

UPDATE: Also, is it possible to use a variable (instead of .0000) if I wanted the number of decimal places to be determined dynamically?

Community
  • 1
  • 1
Prabhu
  • 12,995
  • 33
  • 127
  • 210

4 Answers4

14
string.Format("{0:N4}",decimalValue);

Standard Numeric Format Strings

Custom Numeric Format Strings

To set the precision dynamically you can do the following:

double value = 9.4560000;
int precision = 4;
string format = String.Format("{{0:N{0}}}",precision);
string valuestring = String.Format(format, value);
theChrisKent
  • 15,029
  • 3
  • 61
  • 62
  • 2
    Based on comments below, commas are important too you. This format string adds them correctly. Also, I've edited my response to provide a link to standard numeric format strings for future reference. – theChrisKent Nov 23 '10 at 17:52
1
string.Format({0:#,#0.0000}, decimalValue); 
Gabe
  • 49,577
  • 28
  • 142
  • 181
Joe
  • 122,218
  • 32
  • 205
  • 338
1

Use String.Format -

    decimal d =123.47
    string specifier="{0:0,0.0000}"; // You need to get specifier dynamically here..
    String.Format(specifier, d);      // "123.4700"
Vishal
  • 12,133
  • 17
  • 82
  • 128
1

Try this:

string.Format("{0:#,###.0000}", 9.45600000);

Adding the zeroes in the format forces a zero to be output if there is not a digit to put there.

To add the zeroes with the number of zeroes driven programmatically you could do this:

  int x = 5;
  string fmt = "{0:#,###." + new string('0', x) + "}";
  string.Format(fmt, 9.456000000);
wageoghe
  • 27,390
  • 13
  • 88
  • 116
  • Is it possible to use a variable (instead of .0000) if I wanted the number of decimal places to be determined dynamically? – Prabhu Nov 23 '10 at 17:55
  • 2
    @theChrisKent's answer is better than mine. I had forgotten about the precision specifier. – wageoghe Nov 23 '10 at 18:07