views:

48

answers:

4

Hi All,

As I'm working on C#, I have one field named 'Amount'.

double amount = 10.0;

So, I want the result like '10.0' after converting it to string.

If my value

amount = 10.00, then I want result '10.00' after converting it to string.

So, Basically I want exact result in string as it is in double type. (With precisions).

Thanks in advance.

A: 
string amountString = amount.ToString("N2");

"N2" is the format string used as the first parameter to the .ToString() method.

"N" stands for number, and 2 stands for the number of decimal places.

More on string format's here: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

RPM1984
+2  A: 
string result = string.Format( "{0:f2}", amount );
yhw
+1  A: 

What you ask is not possible. A double in C# is a simple 64-bit floating-point value. It doesn't store precision. You can print your value with one decimal places, or two, as other answers describe, but not in a way that's "preserves" the variable's original precision.

Michael Petrotta
You're right Michael.
nunu
A: 

As @Michael Petratta points out, double doesn't carry with it the precision of the input. If you need that information, you will need to store it yourself. Then you could reconstuct the input string doing something like:

static public string GetPrecisionString( double doubleValue, int precision)
{
    string FormattingString = "{0:f" + precision + "}";
    return string.Format( FormattingString, doubleValue);
}
yhw