When I round off a small negative number it is rounded off to 0.
E.g: decimal.Round(-0.001M, 2)
returns 0.
How can I get the sign if its rounded of to zero. Is there any other better way than to check n<0
then do the round off?
While rounding negative numbers the rounding is done downwards, that is negative numbers are rounded down. If a number such as -2.2 needs to be rounded then the result will be -2 because -2.2 is greater than -2.5 therefore rounded up and result will be -2.
If the digit is 0, 1, 2, 3, or 4, do not change the rounding digit. All digits that are on the righthand side of the requested rounding digit become 0. If the digit is 5, 6, 7, 8, or 9, the rounding digit rounds up by one number.
If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down.
Comparing the bits works for decimal also. Thanks to @JonSkeet, else I'd have never known this trick.
var d = decimal.Round(-0.001M, 2);
bool isNegativeZero = d == decimal.Zero && decimal.GetBits(d).Last() < 0;
Here is the Demo
Is there any other better way than to check n<0 then do the round off?
The simple answer is "no". That is the most straightforward way of doing it. Unless you have a good reason to write code any more complicated than that (that you haven't mentioned in the question), don't do it. You (or another developer) will eventually come back to this code after days or months and wonder why the code was written that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With