Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 834
Prabhu Avatar asked Dec 04 '22 10:12

Prabhu


2 Answers

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);
like image 104
theChrisKent Avatar answered Dec 06 '22 00:12

theChrisKent


string.Format({0:#,#0.0000}, decimalValue); 
like image 23
Joe Avatar answered Dec 05 '22 23:12

Joe