I need to compare two values.
One value is price
which represents current price of something and so decimal
because you actually can buy or sell something by this price.
Another value is estimatedPrice
which is the result of mathematical calculations and so double
because it's just estimation
and you can not actually do any "operations" by this esitmatedPrice
now i want to buy if price < estimatedPrice
.
So should i cast price to double or estimatedPrice to decimal?
I understand that after casting I will get "slighty another" numbers, but it seems I don't have other options.
Decimal is more precise than double because it has more bits of precision.
The Decimal, Double, and Float variable types are different in the way that they store the values. Precision is the main difference where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.
The Decimal, Double, and Float variable types are different in the way that they store the values. Precision is the main difference where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.
It depends on the data. Decimal has greater precision; double has greater range. If the double could be outside the decimal range, you should cast the decimal to double (or indeed you could write a method that returns a result without casting, if the double value is outside the decimal range; see example below).
In this case, it seems unlikely that the double value would be outside the decimal range, so (especially since you're working with price data) you should cast the double to decimal.
Example (could use some logic to handle NaN values):
private static int Compare(double d, decimal m)
{
const double decimalMin = (double)decimal.MinValue;
const double decimalMax = (double)decimal.MaxValue;
if (d < decimalMin) return -1;
if (d > decimalMax) return 1;
return ((decimal)d).CompareTo(m);
}
decimal vs double! - Which one should I use and when?
If you're more concerned with precision, convert to decimal. If you're not, go with doubles.
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