I would like to be able to multiply all members of a given numeric array with each other.
So for example for an array like: [1,2,3,4]
, I would like to get the product of 1*2*3*4
.
I have tried this but didn't work:
/// <summary>
/// Multiplies numbers and returns the product as rounded to the nearest 2 decimal places.
/// </summary>
/// <param name="decimals"></param>
/// <returns></returns>
public static decimal MultiplyDecimals(params decimal[] decimals)
{
decimal product = 0;
foreach (var @decimal in decimals)
{
product *= @decimal;
}
decimal roundProduct = Math.Round(product, 2);
return roundProduct;
}
I am sorry I know this must be simple!
Thanks.
Another opportunity to show off the power of LINQ:
public static decimal MultiplyDecimals(params decimal[] decimals)
{
return decimals.Aggregate(1m, (p, d) => p * d);
}
This
1
(the m
modifier statically types the constant as decimal
) and thenEDIT: Here a variant that includes rounding. I've omitted it, because I don't think it's required (you don't have floating-point problems with decimal
), but here it is for completeness:
public static decimal MultiplyDecimals(params decimal[] decimals)
{
return Math.Round(decimals.Aggregate(1m, (p, d) => p * d), 2);
}
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