Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to compare double and decimal should I cast double to decimal or decimal to double?

Tags:

c#

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.

like image 247
Oleg Vazhnev Avatar asked May 16 '12 04:05

Oleg Vazhnev


People also ask

Which is more precise double or decimal?

Decimal is more precise than double because it has more bits of precision.

What is the difference between float double and decimal?

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.

What is the difference between decimal and double in Salesforce?

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.


2 Answers

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);
}
like image 141
phoog Avatar answered Oct 16 '22 18:10

phoog


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.

like image 26
Yatrix Avatar answered Oct 16 '22 18:10

Yatrix