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.
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);
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);
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