CodeSOD: Dummy Round

Different languages will frequently have similar syntax. Many a pointy-haired-boss has seen this similarity and thus assumed that, if their programmer knows C, then C++ should be easy, and if they know C++ then going into C# must be trivial. I mean, the languages look the same, so they must be the same, right? Boats and cars are steered by wheels, so clearly if you can drive a car you can pilot a boat, and nothing will go wrong.

Andreas S inherited some code that started at C/C++ and was then ported to C#. The original developers were the sort to reinvent wheels wherever possible, so it's no surprise that they kept that going when they moved into C#.

There are, for example, a few methods not supplied in today's code sample. They wrote their own RoundTo, which Andreas describes thus: "RoundTo() is basically equal to Math.Round(), but implemented in a WTF way." There is also a homebrew Sprintf implemented as an "extension method" on Strings.

These all get combined in the method GetStringToRound which doesn't get anything, but seems to just format a string into a rounded off value.

public static string GetStringToRound(double dValue, int iDecimals) { double dDummy = dValue; string sFormat = $"%.{iDecimals}lf"; double dDummyRound = 0.0; string sReturn = ""; for (int i = 0; i <= iDecimals; i++) { dDummyRound = RoundTo(dDummy, i); double dDifferenz = RoundTo(dDummy - dDummyRound, i + 1); if (dDifferenz == 0.0) { sFormat = sFormat.Sprintf("%ld", i); sFormat = "%." + sFormat + "lf"; break; } } if (dValue != dDummyRound) { dValue = dDummyRound; } sReturn = sReturn.Sprintf(sFormat, dValue); return sReturn; }

I think the dummy here is me, because I do not understand any of the logic going on inside that for loop. Why is it even a for loop? I see that we're checking if rounding to i and i+1 decimal places are the same, we know that we don't really need to round farther. Which, sure… but… why?

I'm sure this code works, and I'm sure it's doing what it was intended to do. I also know that there are built-in methods which already do all of this, that are cleaner and easier to read and understand, and don't leave be scratching my head feeling like a dDummy.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.