How to round and format a decimal number correctly?

Possible duplicate:
C # - How to round a decimal value to two decimal places (for output on a page)

I am trying to display decimal places with four decimal places. DB rounds my number to 4 decimal places, but returns a number with a final 0s (due to the decimal precision of the field), 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 the database is 9.45600000, the result after formatting is 9.456

But I need to display 9.4560

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

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

+3
source share
4 answers
string.Format("{0:N4}",decimalValue);

Standard number format strings

Custom Number Format Strings

To dynamically set the accuracy, 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);
+13
source
string.Format({0:#,#0.0000}, decimalValue); 
+1
source

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"
+1

:

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

, .

, , :

  int x = 5;
  string fmt = "{0:#,###." + new string('0', x) + "}";
  string.Format(fmt, 9.456000000);
+1

Source: https://habr.com/ru/post/1776512/


All Articles