.Net division rounding/decimal differences between web servers
I've got a problem that's currently baffling me a bit.
Here's a bit of background: We are in the process of upgrading a asp.net 2.0 web app to .net 4 onto a 64 bit server. We have a test app deployed to both the new and old servers to make sure things work as expected before we go live; both of which point to the same database on another server.
Here's the problem:
double totalGross;
double totalNet = 9999999.00;
float taxRate = 15.00f;
totalGross = totalNet * (1 + (taxRate / 100));
On the old server, the .ToString() on totalGross produces: 11499998.85
On the new server, the .ToString() on totalGross produces: 11499998.6115814
Currently at a loss as to why this might be? The latter value doesn't even represent the first number un-rounded?
By the way - I'm not after ways to correct/improve the code... just after possible reasons why this could happen!
Update
I created a console app and built it in x86 and x64 and ran both versions on the server and it outputted the two different figures. So indeed it does seem to be some sort of loss of precision between 32bit and 64bit when using double. It does surprise me that the 'loss of precision in question is 0.2 this doesn't seem that precise to me and quite a difference?! As someo开发者_Go百科ne suggested it's probably better to use the decimal type (in my defence I didn't write this code :P)
I suppose the old server was a 32bit Machine? Check http://msdn.microsoft.com/en-us/library/system.double.aspx, especially the paragrahp Floating-Point Values and Loss of Precision. Can you force the new server to run the process 32bit, does it change anything?
As the others have mentioned, the platform may be to blame. However, I think that using the Decimal type might be a better choice and will likely not suffer from the same problem as Double. (Every project that I've worked on related to the finance industry uses decimal for calculating monetary transactions). There are no notes about floating-point platform problems on the documentation for Decimal http://msdn.microsoft.com/en-us/library/system.decimal.aspx
"In addition, the result of arithmetic and assignment operations with Double values may differ slightly by platform because of the loss of precision of the Double type. For example, the result of assigning a literal Double value may differ in the 32-bit and 64-bit versions of the .NET Framework." taken from the following Link
精彩评论