Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get - 0 for round off small negative number?

Tags:

c#

rounding

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?

like image 799
Carbine Avatar asked Oct 21 '22 21:10

Carbine


People also ask

How do you round off negatives?

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.

How do you round to the number 0?

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.

Does 0 round up or down?

If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down.


2 Answers

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

like image 50
Sriram Sakthivel Avatar answered Nov 01 '22 11:11

Sriram Sakthivel


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.

like image 41
acfrancis Avatar answered Nov 01 '22 09:11

acfrancis