开发者

Issue with Decimal Rounding in C#

开发者 https://www.devze.com 2023-04-04 19:16 出处:网络
All, I have a set decimal values in C#. I am writing these to fields in a class then serialising this class to an XML data file. However, I have an issue when trying to round a value that is stored

All,

I have a set decimal values in C#. I am writing these to fields in a class then serialising this class to an XML data file. However, I have an issue when trying to round a value that is stored as zero or 0, to four decimal places. I want 0 to be stored as 0.0000. Is this possible using decimal? Of course I can do this without issue when casting to string, and this is not the problem. I have read many threads but none seem to address 开发者_JAVA百科this issue.

Any help would be most appreciated. The code snippit I have is:

// directCost (dCost).
decimal dCost = Convert.ToDecimal(EpiCostValues[(int)epiCostField.directCost]);
dCost = decimal.Round(dCost, 4, MidpointRounding.AwayFromZero);
episodeCostTmp.dCost = dCost;

// indirectCost (iCost).
decimal iCost = Convert.ToDecimal(EpiCostValues[(int)epiCostField.indirectCost]);
iCost = decimal.Round(iCost, 4, MidpointRounding.AwayFromZero);
episodeCostTmp.iCost = iCost;

But this does not force 0 to 0.0000, which is a problem for the required format of the .xml data file.


Add this line into your code

dCost *= 1.0000m;

For Eg:

// directCost (dCost).
decimal dCost = Convert.ToDecimal(EpiCostValues[(int)epiCostField.directCost]);
dCost *= 1.0000m;
dCost = decimal.Round(dCost, 4, MidpointRounding.AwayFromZero);
episodeCostTmp.dCost = dCost;

Hope this Helps :)


The problem you are having is to do with formatting the value as a string, not how it is stored. The value is stored in binary, it's the part where you change it to a string that has the problem. You could try : string.Format("{0:0.0000}", iCost);


You won't see the additional precision until you format the output of your number. E.g. nothing will say the number is 1.0000 rather than simply 1 or 1.0. However when the number is 1.2345 - you will see that level of precision.

So what you've done is fine. Format it to 4 decimal places when you write it to your file, and you will get .0000 when it's a whole number, or .2345 (or whatever it is) when the precision is used.


I think when serializing the values of all fields are converted to string with the ToString() method. maybe you could override this method in a new type which inherits from decimal or write an extension method (don't know if it works though).

0

精彩评论

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

关注公众号