Carbine
Carbine

Reputation: 7903

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

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?

Upvotes: 5

Views: 953

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73472

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

Upvotes: 2

acfrancis
acfrancis

Reputation: 3671

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.

Upvotes: 1

Related Questions