Question

Can you simplify this Math.Ceiling expression

decimal total
decimal? quantity, multiplier
int? days

total = (decimal)Math.Ceiling((double)quantity.Value * (double)days.Value * (double)multiplier);

EDIT I forgot to mention that this is Silverlight code, hence all the casts into double.

Was it helpful?

Solution

Why would you want to convert everything to double? I would use:

total = decimal.Ceiling(quantity.Value * days.Value * multiplier.Value);

(You could use Math.Ceiling(decimal) instead, but I feel it's clearer that it's using decimal if you use decimal.Ceiling.)

Converting everything to double, performing the arithmetic there, and then converting back to decimal is very likely to lose information. You should very, very rarely be converting between double and decimal IMO.

OTHER TIPS

You didn't provide a whole lot of info, but here's one idea.

You use Nullable Types (types that end with a ?), but don't seem to actually check if they are null. (There might be code you omitted). If you know they won't be null, don't use nullable types. That will get rid of all the .Value terms in your expression.

This would change your expression to:

total = (decimal)Math.Ceiling((double)quantity * (double)days * (double)multiplier);

I don't know why you're casting each multiplier to double. I'd prefer multiplying them all together before casting to double. (check carefully for loss of precision.)

This would change your expression to:

total = (decimal)Math.Ceiling((double)(quantity * days * multiplier));

Overall, that looks simpler to me, and should be just as good.
(only testing will tell for sure!)

How about:

decimal total;
decimal? quantity = null, multiplier = null;
int? days = null;

total = Math.Ceiling(quantity ?? 0 * days ?? 0 * multiplier ?? 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top