Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET decimal.Negate vs multiplying by -1

Are there any differences between decimal.Negate(myDecimal) and myDecimal * -1 (except maybe readability)?

like image 749
anchandra Avatar asked Aug 05 '10 06:08

anchandra


People also ask

Which method is used to multiply two specified decimal values?

Decimal.Multiply () Method in C#. The Decimal.Add () method in C# is used to multiply two specified Decimal values.

What does negate mean in math?

The value to negate. A decimal number with the value of d, but the opposite sign. Zero, if d is zero. The following code example uses the Negate method to change the sign of several Decimal values.

How to multiply two decimal values in C?

The Decimal.Add () method in C# is used to multiply two specified Decimal values. Above, va1 is the multiplicand, whereas val2 is the multiplier. Let us now see an example to implement the Decimal.Multiply () method −

How do you know if a decimal has a fractional part?

If d has a fractional part, the next whole Decimal number toward negative infinity that is less than d. If d doesn't have a fractional part, d is returned unchanged. Note that the method returns an integral value of type Decimal. The following example illustrates the Floor method and contrasts it with the Ceiling method.


1 Answers

I suspect Negate exists because there's a unary minus operator (op_UnaryNegation), and it's good practice to have methods representing the equivalent functionality so that languages which don't support operator overloading can still achieve the same result.

So instead of comparing it with myDecimal * -1 it may be helpful to think of it as being an alternative way of writing -myDecimal.

(I believe it's also optimised - given the way floating point works, negating a value is much simpler than normal multiplication; there's just a bit to flip. No need to perform any actual arithmetic.)

like image 83
Jon Skeet Avatar answered Nov 06 '22 10:11

Jon Skeet