Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert object to Decimal

I'm trying to convert an object with the value 0.39999999999999997 to a decimal variable without losing the precision.

object d = 0.39999999999999997;

I've tried the following methods.

decimal val1 = Convert.ToDecimal(d); // val1 = 0.4
object val2 = Convert.ChangeType(d, Type.GetType("System.Decimal")); // val2 = 0.4
decimal val3 = decimal.Parse(d.ToString()); // val3 = 0.4
decimal val4 = (Decimal) d; // val4 = 0.4

I know the this is not a problem with the decimal data type not being able to store this value as illustrated below.

decimal val5 = 0.39999999999999997m; // val5 = 0.39999999999999997;

How do I convert this object to decimal without losing the precision?

I'm using .NET Framework 3.5 if that matters.

like image 516
Chathura W Avatar asked Jul 27 '11 07:07

Chathura W


2 Answers

I think this is the code you looking for:

object d = 0.39999999999999997;
//Unbox value
double doubleVal = (double)d;

//Convert to string. R format specifier gives a string that can round-trip to an identical number.  
//Without R ToString() result would be doubleAsString = "0.4"
string doubleAsString = doubleVal.ToString("R"); 

//Now that you have doubleAsString = "0.39999999999999997" parse it!
decimal decimalVal = decimal.Parse(doubleAsString);
like image 73
Renatas M. Avatar answered Sep 22 '22 12:09

Renatas M.


For this to work you will need to assign it similarly

object d = 0.39999999999999997M;

There is no way for the object to maintain the precision unless you force it to. (If this is not the actual code, you will need to show as how its assigned)

Only then would something like this would work decimal dec = Convert.ToDecimal(d);

like image 29
V4Vendetta Avatar answered Sep 20 '22 12:09

V4Vendetta