Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal? to double?

Tags:

c#

nullable

I am wondering what would be the best way (in the sense of safer and succinct) to convert from one nullable type to another "compatible" nullable type.

Specifically, converting from decimal? to double? can be done using:

public double? ConvertToNullableDouble(decimal? source)
{
    return source.HasValue ? Convert.ToDouble(source) : (double?) null;
}

Is there any better way to do this? Maybe leveraging a standard conversion?

like image 401
Camilo Martinez Avatar asked May 02 '13 21:05

Camilo Martinez


People also ask

How do you double decimals?

To multiply decimals, first multiply as if there is no decimal. Next, count the number of digits after the decimal in each factor. Finally, put the same number of digits behind the decimal in the product.

Is decimal the same as double?

Double (aka double): A 64-bit floating-point number. Decimal (aka decimal): A 128-bit floating-point number with a higher precision and a smaller range than Single or Double.

What does convert ToDouble () do?

The Convert. ToDouble() method in C# converts the specified string representation of a number to an equivalent double-precision floating-point number, using the specified culture-specific formatting information.

Do Doubles allow Decimals?

double is a 64-bit IEEE 754 double precision Floating Point Number – 1 bit for the sign, 11 bits for the exponent, and 52* bits for the value. double has 15 decimal digits of precision.


2 Answers

Built in casts for the win! Just tested this in VS2012 and VS2010:

 decimal? numberDecimal = new Decimal(5); 
 decimal? nullDecimal = null;
 double? numberDouble = (double?)numberDecimal; // = 5.0
 double? nullDouble = (double?)nullDecimal;     // = null

Just using an explicit cast will cast null to null, and the internal decimal value to double. Success!

like image 77
Avner Shahar-Kashtan Avatar answered Oct 20 '22 21:10

Avner Shahar-Kashtan


In general, if you want o convert from any data type to the other as long as they are compatible, use this:

    Convert.ChangeType(your variable, typeof(datatype you want convert to));

for example:

    string str= "123";
    int value1 = (int)Convert.ChangeType(str, typeof(int));
    float? value2 = (float?)Convert.ChangeType(str, typeof(float));
    ...................................

A little bit further, if you want it to be more safer, you can add a try catch on it:

string str= "123";
try
{
    int value1 = (int)Convert.ChangeType(str, typeof(int));
    int? value2 = (int?)Convert.ChangeType(str, typeof(int));
    float value3 = (float)Convert.ChangeType(str, typeof(float));
    float? value4 = (float?)Convert.ChangeType(str, typeof(float));
}
catch(Exception ex)
{
  // do nothing, or assign a default value
}

this is tested under VS 2010

like image 44
www.diwatu.com Avatar answered Oct 20 '22 20:10

www.diwatu.com