开发者

Decimal in .NET

I have a decimal in .NET and I need to store it to a column开发者_如何学C in a typed dataset that is a string. I need the decimal to be stored to two decimal places. Even though I use Math.Round(value,2) and I do a ToString(), it doesnt work.

Any ideas and suggestions are appreciated!


You need to do decimalVar.ToString ("#.##");

or

decimal value = 1.2345;
string rounded = value.ToString("d2");

See .NET Format String Cheat Sheets


Use this:

[decimal].ToString("F") or [decimal].ToString("F2")


decimal myDecimal = 123.456;
string myString = myDecimal.toString("N2");


Declare your value as 0.0000M instead 0. Example below

decimal a = 1.6644M;  

Math.Round(a, 2); 

returns 1.66


To avoid as much as it possible "strange" floating point calculation problem I would suggest:

First: define your presicion: in your case it seems to be 2 numbers after point. Second: convert decimal to integer

int iValue = (int)(Math.Round(decimalValue) * 100); // 10 ^ 2 of precision

Third: store in DataSet that string and not floated point value string. (why not integer at this point?)

If you need to show to user the value stored in DataSet, make an inverse operation.

EDIT:

Having in this way a solid data on you datamodel which is DataSet you can manage your presentation layer DataView/DataBinging... in a way you like in order to support any culture of your client and decrease probbability to have "floating point ariphmetics mess".

Regards.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜