patterncsharpMinor
Excessive number casting & conversion?
Viewed 0 times
conversionnumberexcessivecasting
Problem
I’m trying to improve my code’s "signal to noise ratio", hence would appreciate any tips on improving this, what appears to be smelly code. Perhaps there could also be potential performance improvements to be made here:
Unfortunately, I don’t have control over the types of properties, as the types of
public class PricingInfoDto
{
[DataMember]
public decimal ListPrice { get; set; }
[DataMember]
public decimal Contribution
{
get
{
var contributionAmount = (1 + TaxRate) * (float)ListPrice * (ContributionPercentage / 100);
return Convert.ToDecimal(Math.Round(Math.Min(ContributionMaximumAmount, contributionAmount), 2));
}
private set
{
// For NHibernate Map
}
}
public float TaxRate { get; set; }
public double ContributionMaximumAmount { get; set; }
public float ContributionPercentage { get; set; }
}Unfortunately, I don’t have control over the types of properties, as the types of
ContributionMaximumAmount & ContributionPercentage are enforced by the ADO.NET and the public DataMember is expected to be Decimal.Solution
You are ignoring the whole point of decimals. Which is to avoid rounding errors from floating point caclulations.
You must cast
You must cast
TaxRate, ListPrice, ContributionPercentage, etc. to Decimal and only then do your calculations using Decimal values. Casting at some point is unavoidable, if you have no control over signatures. You can, however, implement a wrapper, which would do the casting and expose Decimal properties. That will make your code more pretty.Context
StackExchange Code Review Q#47958, answer score: 5
Revisions (0)
No revisions yet.