开发者

C# Get exact string formation from 'double' type

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.


string result = string.Format( "{0:f2}", amount );


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.


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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜