开发者

How to round and format a decimal correctly? [duplicate]

开发者 https://www.devze.com 2023-01-27 02:57 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: c# - How do I round a decimal value to 2 decimal places (for output on a page)
This question already has answers here: Closed 10 years ago.

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 nu开发者_如何学JAVAmber of decimal places to be determined dynamically?


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);


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


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"


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消