I’m experiencing a small issue when I’m trying to round the number 1.785m to two digits. The number can probably not be represented correctly using the decimal data type, since it’s still a floating point number.
I would be excepting the result 1.79m but it’s rounded/present as 1.78m. My question is, how can I achieve a correct result?
My current workaround looks like this:
long l = (long)(1.785m * 1000m);
bool roundUp = l % 10 >= 5;
l = l / 10;
if(roundUp)
l++;
decimal result = l \ 100;
You'll need to explicitly set the rounding mode to
MidpointRounding.AwayFromZero:But as per those code comments: this does exactly what it says on the tin for negative numbers, which will round down rather than up. If you need 0.5 to always round up you'll want
Math.ToPositiveInfinity, but depending on your version of .NET, that enum may not be supported.