Reputation: 1190
I was on a task of porting C++ code to C#. There was a bug reported by client in my code. When I did debugging, here is what I got...
C++ Code:
double d = -0.0000000000018736038338473693;
String temp = String(SimpleRoundTo(d, -12))); // SimpleRoundTo() is from delphi
// temp is having -1E-12
C# Code:
double d = -0.0000000000018736038338473693;
string temp = (Math.Round(d, 12)).ToString();
// temp is having -2E-12
I did check the overloads by Math.Round(), not getting how to get the same result.
Upvotes: 0
Views: 317
Reputation: 612794
The answer that the C++ version is giving is just plain wrong. That should be obvious. It's clear that 2E-12
is the correct answer since SimpleRoundTo
, just like Math.Round
, rounds to nearest.
So, if you wish to reproduce the erroneous output of the C++ version in C# you'll need to translate the Delphi RTL code to C#. That would involve working out exactly what SimpleRoundTo
and the String()
conversion does. Or p/invoke to a C++ DLL.
I would tackle this by trying to work out what the original code is intended to do. Express this in a mathematical way rather than in terms of the RTL functions. Once you have a clear specification of what you intend the code to do, code it in C# using the natural C# mechanisms. In other words, don't attempt a literal translation because one probably does not exist. Instead understand the intent of the original code and implement it from scratch in C#.
Looking at your code you perform rounding, and then convert to text. I would be looking for an approach that performed the rounding as part of the conversion to text.
Upvotes: 4