Are there any differences between decimal.Negate(myDecimal)
and myDecimal * -1
(except maybe readability)?
Decimal.Multiply () Method in C#. The Decimal.Add () method in C# is used to multiply two specified Decimal values.
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.
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 −
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.
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.)
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